"""
Deploy all missing Genesis schemas and Qdrant collections.
Run: python deploy_schemas_and_collections.py
"""
import sys
import traceback

sys.path.append('E:/genesis-system/data/genesis-memory')

results = {
    'pg_unified_schema': None,
    'pg_rlm_schema': None,
    'pg_alpha_evolve_schema': None,
    'pg_aiva_rlm_schema': None,
    'qdrant_collections': [],
    'errors': [],
}

# ---- PostgreSQL schema deployments ----
try:
    import psycopg2
    from elestio_config import PostgresConfig

    conn = psycopg2.connect(**PostgresConfig.get_connection_params())
    conn.autocommit = False
    cur = conn.cursor()
    print('PG connected.')

    # 1. Unified schema (new tables)
    try:
        with open('E:/genesis-system/data/genesis_unified_schema.sql', 'r') as f:
            sql = f.read()
        cur.execute(sql)
        conn.commit()
        results['pg_unified_schema'] = 'DEPLOYED'
        print('Unified schema: DEPLOYED')
    except Exception as e:
        conn.rollback()
        results['pg_unified_schema'] = f'ERROR: {e}'
        results['errors'].append(f'unified_schema: {e}')
        print(f'Unified schema ERROR: {e}')

    # 2. RLM schema (idempotent re-run)
    try:
        with open('E:/genesis-system/scripts/rlm_create_tables.sql', 'r') as f:
            sql = f.read()
        # Strip GRANT lines that fail if 'genesis' user doesn't exist
        safe_sql = '\n'.join(
            line for line in sql.splitlines()
            if not line.strip().upper().startswith('GRANT')
        )
        cur.execute(safe_sql)
        conn.commit()
        results['pg_rlm_schema'] = 'VERIFIED (already existed)'
        print('RLM schema: VERIFIED')
    except Exception as e:
        conn.rollback()
        results['pg_rlm_schema'] = f'ERROR: {e}'
        results['errors'].append(f'rlm_schema: {e}')
        print(f'RLM schema ERROR: {e}')

    # 3. Alpha Evolve schema (idempotent)
    try:
        with open('E:/genesis-system/scripts/alpha_evolve_create_tables.sql', 'r') as f:
            sql = f.read()
        cur.execute(sql)
        conn.commit()
        results['pg_alpha_evolve_schema'] = 'VERIFIED (already existed)'
        print('Alpha Evolve schema: VERIFIED')
    except Exception as e:
        conn.rollback()
        results['pg_alpha_evolve_schema'] = f'ERROR: {e}'
        results['errors'].append(f'alpha_evolve_schema: {e}')
        print(f'Alpha Evolve schema ERROR: {e}')

    # 4. AIVA RLM schema (idempotent)
    try:
        with open('E:/genesis-system/scripts/aiva_rlm_schema.sql', 'r') as f:
            sql = f.read()
        cur.execute(sql)
        conn.commit()
        results['pg_aiva_rlm_schema'] = 'VERIFIED (already existed)'
        print('AIVA RLM schema: VERIFIED')
    except Exception as e:
        conn.rollback()
        results['pg_aiva_rlm_schema'] = f'ERROR: {e}'
        results['errors'].append(f'aiva_rlm_schema: {e}')
        print(f'AIVA RLM schema ERROR: {e}')

    # Verify final table list
    cur.execute("""
        SELECT table_schema, table_name
        FROM information_schema.tables
        WHERE table_schema IN ('public','aiva_rlm','genesis')
        ORDER BY table_schema, table_name
    """)
    all_tables = [(r[0], r[1]) for r in cur.fetchall()]
    results['final_table_count'] = len(all_tables)
    results['final_tables'] = all_tables
    print(f'Final table count: {len(all_tables)}')

    cur.close()
    conn.close()

except Exception as e:
    results['errors'].append(f'pg_connection: {e}')
    print(f'PG connection ERROR: {e}')
    traceback.print_exc()

# ---- Qdrant collections ----
try:
    from qdrant_client import QdrantClient
    from qdrant_client.models import Distance, VectorParams
    from elestio_config import QdrantConfig

    qc = QdrantClient(url=QdrantConfig().url, api_key=QdrantConfig().api_key)
    existing = [c.name for c in qc.get_collections().collections]
    print(f'Existing Qdrant collections: {existing}')

    needed = [
        ('genesis_memories', 768),
        ('research_reports', 768),
        ('tradie_knowledge', 768),
        ('product_knowledge', 768),
    ]

    for name, dim in needed:
        if name in existing:
            results['qdrant_collections'].append(f'{name}: ALREADY EXISTS')
            print(f'Qdrant {name}: already exists')
        else:
            try:
                qc.create_collection(
                    name,
                    vectors_config=VectorParams(size=dim, distance=Distance.COSINE)
                )
                results['qdrant_collections'].append(f'{name}: CREATED')
                print(f'Qdrant {name}: CREATED')
            except Exception as e:
                results['qdrant_collections'].append(f'{name}: ERROR {e}')
                results['errors'].append(f'qdrant_{name}: {e}')
                print(f'Qdrant {name} ERROR: {e}')

    results['qdrant_final'] = [c.name for c in qc.get_collections().collections]

except Exception as e:
    results['errors'].append(f'qdrant_connection: {e}')
    print(f'Qdrant ERROR: {e}')
    traceback.print_exc()

# ---- Write results ----
import json
with open('E:/genesis-system/scripts/deploy_results.json', 'w') as f:
    json.dump(results, f, indent=2, default=str)

print('\n=== DEPLOYMENT COMPLETE ===')
print(f"PG Unified:      {results.get('pg_unified_schema')}")
print(f"PG RLM:          {results.get('pg_rlm_schema')}")
print(f"PG AlphaEvolve:  {results.get('pg_alpha_evolve_schema')}")
print(f"PG AIVA RLM:     {results.get('pg_aiva_rlm_schema')}")
print(f"Total PG tables: {results.get('final_table_count', '?')}")
print(f"Qdrant:          {results.get('qdrant_collections')}")
print(f"Errors:          {results.get('errors')}")
print('Results JSON: E:/genesis-system/scripts/deploy_results.json')
