
import sys
import os

# Add parent directory to path to allow import of backend.database
sys.path.append(os.path.join(os.path.dirname(__file__), "../../"))

# Import everything to ensure metadata is populated
from backend.database import engine, Base, Company, Contact, Industry, JobRolePattern, Persona, Signal, EnrichmentData, RoboticsCategory, ImportLog, ReportedMistake, MarketingMatrix

def migrate():
    print("Migrating Database Schema...")
    
    try:
        # Hacky migration for MarketingMatrix: Drop if exists to enforce new schema
        with engine.connect() as con:
            print("Dropping old MarketingMatrix table to enforce schema change...")
            try:
                from sqlalchemy import text
                con.execute(text("DROP TABLE IF EXISTS marketing_matrix"))
                print("Dropped marketing_matrix.")
            except Exception as e:
                print(f"Could not drop marketing_matrix: {e}")
                
    except Exception as e:
        print(f"Pre-migration cleanup error: {e}")

    # This creates 'personas' table AND re-creates 'marketing_matrix'
    Base.metadata.create_all(bind=engine)
    print("Migration complete. 'personas' table created and 'marketing_matrix' refreshed.")

if __name__ == "__main__":
    migrate()
