#!/usr/bin/env python3
"""
Run Django migrations on the production server.
Upload to /home/xygbfpsg/phingrazuri/ and run: python run_migrations.py
"""
import os
import sys
import subprocess
from datetime import datetime

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')

# Load .env
try:
    from dotenv import load_dotenv
    load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env'), override=True)
    print("Loaded .env")
except ImportError:
    pass

def run(cmd, ignore_errors=False):
    print(f"\n>>> {cmd}")
    result = subprocess.run(cmd, shell=True, text=True, capture_output=True)
    if result.stdout:
        print(result.stdout)
    if result.stderr:
        print(result.stderr)
    if result.returncode != 0 and not ignore_errors:
        print(f"FAILED (exit {result.returncode})")
    else:
        print(f"OK (exit {result.returncode})")
    return result.returncode == 0

print(f"\n{'='*60}")
print(f"  Migration Runner  {datetime.now():%Y-%m-%d %H:%M:%S}")
print(f"{'='*60}")

py = sys.executable

# Step 1: verify DB connection first
print("\n[1] Verifying DB connection...")
import django
django.setup()
from django.db import connection
try:
    with connection.cursor() as c:
        c.execute("SELECT 1")
    print("  DB connection OK")
except Exception as e:
    print(f"  DB connection FAILED: {e}")
    sys.exit(1)

# Step 2: run makemigrations for each app
print("\n[2] Making migrations...")
for app in ['users', 'loans', 'reports', 'utils', 'payments', 'expenses']:
    run(f"{py} manage.py makemigrations {app}", ignore_errors=True)

# Step 3: run migrate
print("\n[3] Running migrate...")
ok = run(f"{py} manage.py migrate --run-syncdb")

if not ok:
    print("\n  Trying with --fake-initial...")
    run(f"{py} manage.py migrate --fake-initial", ignore_errors=True)

# Step 4: create cache table (needed for db cache backend)
print("\n[4] Creating cache table...")
run(f"{py} manage.py createcachetable", ignore_errors=True)

# Step 5: collect static files
print("\n[5] Collecting static files...")
run(f"{py} manage.py collectstatic --noinput", ignore_errors=True)

# Step 6: verify critical tables now exist
print("\n[6] Verifying critical tables...")
critical = [
    'django_session', 'django_migrations', 'users',
    'loans', 'utils_systemsetting', 'utils_notification',
    'auth_permission', 'django_content_type',
]
with connection.cursor() as c:
    c.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE()")
    existing = {r[0].lower() for r in c.fetchall()}

all_ok = True
for table in critical:
    if table.lower() in existing:
        print(f"  OK  {table}")
    else:
        print(f"  MISSING  {table}")
        all_ok = False

print(f"\n{'='*60}")
if all_ok:
    print("  All critical tables present. Restart your app in cPanel.")
else:
    print("  Some tables still missing. Check errors above.")
print(f"{'='*60}\n")
