import sqlite3
import os

DB_PATH = "/data/companies_v3_fixed_2.db"

# Fallback for local testing
if not os.path.exists(DB_PATH):
    DB_PATH = "company-explorer/companies_v3_fixed_2.db"

def add_column(cursor, table, column, type_def):
    try:
        cursor.execute(f"ALTER TABLE {table} ADD COLUMN {column} {type_def}")
        print(f"✅ Added {table}.{column}")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e).lower():
            print(f"ℹ️  {table}.{column} already exists")
        else:
            print(f"❌ Error adding {table}.{column}: {e}")

def migrate():
    print(f"Starting migration for {DB_PATH}...")
    if not os.path.exists(DB_PATH):
        print(f"❌ Database not found at {DB_PATH}")
        return

    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    # Columns for 'companies' table
    company_cols = [
        ("street", "TEXT"),
        ("zip_code", "TEXT"),
        ("city", "TEXT"),
        ("country", "TEXT DEFAULT 'DE'"),
        ("calculated_metric_name", "TEXT"),
        ("calculated_metric_value", "FLOAT"),
        ("calculated_metric_unit", "TEXT"),
        ("standardized_metric_value", "FLOAT"),
        ("standardized_metric_unit", "TEXT"),
        ("metric_source", "TEXT"),
        ("metric_proof_text", "TEXT"),
        ("metric_source_url", "TEXT"),
        ("metric_confidence", "FLOAT"),
        ("metric_confidence_reason", "TEXT"),
        ("ai_opener", "TEXT"),
        ("ai_opener_secondary", "TEXT"),
        ("research_dossier", "TEXT")
    ]

    # Columns for 'industries' table
    industry_cols = [
        ("status_notion", "TEXT"),
        ("is_focus", "BOOLEAN DEFAULT 0"),
        ("pains", "TEXT"),
        ("gains", "TEXT"),
        ("notes", "TEXT"),
        ("priority", "TEXT"),
        ("ops_focus_secondary", "BOOLEAN DEFAULT 0"),
        ("strategy_briefing", "TEXT"),
        ("metric_type", "TEXT"),
        ("min_requirement", "FLOAT"),
        ("whale_threshold", "FLOAT"),
        ("proxy_factor", "FLOAT"),
        ("scraper_search_term", "TEXT"),
        ("scraper_keywords", "TEXT"),
        ("standardization_logic", "TEXT"),
        ("primary_category_id", "INTEGER"),
        ("secondary_category_id", "INTEGER")
    ]

    # Columns for 'contacts' table
    contact_cols = [
        ("so_contact_id", "INTEGER"),
        ("so_person_id", "INTEGER"),
        ("role", "TEXT"),
        ("status", "TEXT"),
        ("unsubscribe_token", "TEXT"),
        ("is_primary", "BOOLEAN DEFAULT 0")
    ]

    for col, dtype in company_cols:
        add_column(cursor, "companies", col, dtype)

    for col, dtype in industry_cols:
        add_column(cursor, "industries", col, dtype)

    for col, dtype in contact_cols:
        add_column(cursor, "contacts", col, dtype)

    conn.commit()
    conn.close()
    print("Migration complete.")

if __name__ == "__main__":
    migrate()
