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

output_lines = []

try:
    from elestio_config import PostgresConfig
    import psycopg2
    params = PostgresConfig.get_connection_params()
    output_lines.append(f"Connecting to: {params.get('host','?')} / {params.get('dbname','?')}")
    conn = psycopg2.connect(**params)
    cur = conn.cursor()
    cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema='public' ORDER BY table_name")
    tables = [r[0] for r in cur.fetchall()]
    output_lines.append(f"TABLES: {tables}")
    if 'tradie_leads' in tables:
        cur.execute("SELECT COUNT(*) FROM tradie_leads")
        output_lines.append(f"tradie_leads rows: {cur.fetchone()[0]}")
    else:
        output_lines.append("No tradie_leads table found")
    conn.close()
    output_lines.append("DB_OK")
except Exception as e:
    output_lines.append(f"DB_ERROR: {type(e).__name__}: {e}")

with open('E:/genesis-system/scripts/db_check_result.txt', 'w') as f:
    f.write('\n'.join(output_lines))

print('Done - see db_check_result.txt')
