#!/usr/bin/env python3
"""Migration script to create CRM tables (crm_contacts, crm_deals, crm_companies).

Usage:
    python3 scripts/migrate_crm_tables.py

This ensures the new CRM models are materialized in the database.
Works with both SQLite and PostgreSQL backends.
"""

import sys
import os

# Ensure the app directory is on the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from app import create_app
from app.models import db


def run_migration():
    """Create all missing tables including CRM models."""
    app = create_app()
    with app.app_context():
        # db.create_all() is safe — it only creates tables that don't exist yet
        db.create_all()

        # Verify the new tables exist by checking metadata
        from sqlalchemy import inspect
        inspector = inspect(db.engine)
        tables = inspector.get_table_names()

        new_tables = ["crm_contacts", "crm_deals", "crm_companies"]
        for table in new_tables:
            if table in tables:
                print(f"  ✓ Table '{table}' exists")
            else:
                print(f"  ✗ Table '{table}' is MISSING")
                return 1

        print(f"\nAll {len(new_tables)} CRM tables verified in database.")
        print(f"Total tables: {len(tables)}")
        return 0


if __name__ == "__main__":
    print("Running CRM table migration...")
    sys.exit(run_migration())