#!/usr/bin/env python
"""
Simple Database Deployment Script - No Hanging
"""

import os
import sys
import django
from pathlib import Path

# Set production database credentials
os.environ['DB_NAME'] = 'xygbfpsg_graz'
os.environ['DB_USER'] = 'xygbfpsg_graz'
os.environ['DB_PASSWORD'] = ',qdN3O_!}oC67(]W'
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_PORT'] = '3306'

# Setup Django
BASE_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(BASE_DIR))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.core.management import call_command
from django.db import connection

def main():
    print("="*60)
    print("SIMPLE DATABASE DEPLOYMENT")
    print("="*60)
    
    # Step 1: Check connection
    print("\n[1/5] Checking database connection...")
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
        print("✓ Database connected")
    except Exception as e:
        print(f"✗ Connection failed: {e}")
        return False
    
    # Step 2: Show pending migrations
    print("\n[2/5] Checking pending migrations...")
    try:
        from django.db.migrations.executor import MigrationExecutor
        executor = MigrationExecutor(connection)
        plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
        if plan:
            print(f"✓ Found {len(plan)} pending migrations")
        else:
            print("✓ No pending migrations")
    except Exception as e:
        print(f"⚠ Could not check: {e}")
    
    # Step 3: Apply migrations
    print("\n[3/5] Applying migrations...")
    try:
        call_command('migrate', '--noinput')
        print("✓ Migrations applied")
    except Exception as e:
        print(f"✗ Migration failed: {e}")
        return False
    
    # Step 4: Verify critical tables
    print("\n[4/5] Verifying tables...")
    try:
        with connection.cursor() as cursor:
            cursor.execute("SHOW TABLES")
            tables = [row[0] for row in cursor.fetchall()]
            print(f"✓ Found {len(tables)} tables")
    except Exception as e:
        print(f"⚠ Could not verify: {e}")
    
    print("\n" + "="*60)
    print("✅ DEPLOYMENT COMPLETED SUCCESSFULLY")
    print("="*60)
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
