import sqlite3
import os

DB_PATH = "/app/companies_v3_fixed_2.db"

# If running outside container, adjust path
if not os.path.exists(DB_PATH):
    DB_PATH = "companies_v3_fixed_2.db"

def upgrade():
    print(f"Upgrading database at {DB_PATH}...")
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    # 2. Add Columns to Contact
    try:
        cursor.execute("ALTER TABLE contacts ADD COLUMN so_contact_id INTEGER")
        print("✅ Added column: so_contact_id")
    except sqlite3.OperationalError as e:
        if "duplicate column" in str(e):
            print("ℹ️  Column so_contact_id already exists")
        else:
            print(f"❌ Error adding so_contact_id: {e}")

    try:
        cursor.execute("ALTER TABLE contacts ADD COLUMN so_person_id INTEGER")
        print("✅ Added column: so_person_id")
    except sqlite3.OperationalError as e:
        if "duplicate column" in str(e):
            print("ℹ️  Column so_person_id already exists")
        else:
            print(f"❌ Error adding so_person_id: {e}")

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

if __name__ == "__main__":
    upgrade()
