#!/usr/bin/env python
"""
Clean up custom templates that might be overriding built-in ones.
Remove custom 'wedding_invitation' from database so built-in template is used.
"""

import os
import sys
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Import database config
from database import DATABASE_URL, Base
from models import WhatsAppTemplate

def cleanup():
    """Delete custom wedding_invitation template from database."""
    
    # Create engine and session
    engine = create_engine(DATABASE_URL)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    db = SessionLocal()
    
    try:
        # Check if custom wedding_invitation exists
        custom = db.query(WhatsAppTemplate).filter(
            WhatsAppTemplate.template_key == 'wedding_invitation'
        ).first()
        
        if custom:
            print(f"✓ Found custom 'wedding_invitation' in database")
            print(f"  - meta_name: {custom.meta_name}")
            print(f"  - body_params: {custom.body_params}")
            db.delete(custom)
            db.commit()
            print(f"✓ Deleted custom 'wedding_invitation'")
            print(f"✓ Built-in 'wedding_invitation' will now be used")
        else:
            print(f"✓ No custom 'wedding_invitation' found in database")
        
        # List remaining custom templates
        remaining = db.query(WhatsAppTemplate).all()
        if remaining:
            print(f"\n✓ Remaining custom templates: {len(remaining)}")
            for t in remaining:
                print(f"  - {t.template_key} ({t.meta_name})")
        else:
            print(f"\n✓ No custom templates in database (only built-in templates available)")
            
    except Exception as e:
        print(f"✗ Error: {e}")
        db.rollback()
        sys.exit(1)
    finally:
        db.close()

if __name__ == "__main__":
    cleanup()
