#!/usr/bin/env python
"""
Production deployment script for Client Approval System
Specifically designed for cPanel production environments
"""

import os
import sys
import django
from pathlib import Path

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

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


def print_section(title):
    """Print a formatted section header"""
    print("\n" + "=" * 80)
    print(f"  {title}")
    print("=" * 80 + "\n")


def check_field_exists(table, field):
    """Check if a field exists in the database"""
    try:
        with connection.cursor() as cursor:
            cursor.execute(f"""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = '{table}' 
                AND COLUMN_NAME = '{field}'
            """)
            return cursor.fetchone() is not None
    except Exception as e:
        print(f"Error checking field {field}: {e}")
        return False


def check_approval_fields():
    """Check which approval fields exist"""
    print_section("Checking Existing Approval Fields")
    
    fields_to_check = [
        ('approval_reason', 'approval_reason'),
        ('approved_at', 'approved_at'),
        ('approved_by_id', 'approved_by_id'),
        ('rejection_reason', 'rejection_reason'),
        ('rejected_at', 'rejected_at'),
        ('rejected_by_id', 'rejected_by_id'),
    ]
    
    existing_fields = []
    missing_fields = []
    
    for field_name, column_name in fields_to_check:
            if check_field_exists('users', column_name):
                existing_fields.append(field_name)
                print(f"[OK] {field_name} exists")
            else:
                missing_fields.append(field_name)
                print(f"[MISSING] {field_name} missing")
    
    return existing_fields, missing_fields


def deploy_sql_directly():
    """Deploy the approval fields using direct SQL"""
    print_section("Deploying Approval Fields via SQL")
    
    try:
        with connection.cursor() as cursor:
            # Check and add approval_reason
            if not check_field_exists('users', 'approval_reason'):
                cursor.execute("""
                    ALTER TABLE `users` 
                    ADD COLUMN `approval_reason` TEXT NULL
                """)
                print("[OK] Added approval_reason")
            
            # Check and add approved_at
            if not check_field_exists('users', 'approved_at'):
                cursor.execute("""
                    ALTER TABLE `users` 
                    ADD COLUMN `approved_at` DATETIME NULL
                """)
                print("[OK] Added approved_at")
            
            # Check and add approved_by_id
            if not check_field_exists('users', 'approved_by_id'):
                cursor.execute("""
                    ALTER TABLE `users` 
                    ADD COLUMN `approved_by_id` CHAR(32) NULL
                """)
                print("[OK] Added approved_by_id")
            
            # Check and add rejected_at
            if not check_field_exists('users', 'rejected_at'):
                cursor.execute("""
                    ALTER TABLE `users` 
                    ADD COLUMN `rejected_at` DATETIME NULL
                """)
                print("[OK] Added rejected_at")
            
            # Check and add rejected_by_id
            if not check_field_exists('users', 'rejected_by_id'):
                cursor.execute("""
                    ALTER TABLE `users` 
                    ADD COLUMN `rejected_by_id` CHAR(32) NULL
                """)
                print("[OK] Added rejected_by_id")
            
            # Check and add rejection_reason
            if not check_field_exists('users', 'rejection_reason'):
                cursor.execute("""
                    ALTER TABLE `users` 
                    ADD COLUMN `rejection_reason` TEXT NULL
                """)
                print("[OK] Added rejection_reason")
            
            print("\n[OK] All fields deployed successfully")
            return True
            
    except Exception as e:
        print(f"\n[FAIL] SQL deployment failed: {e}")
        return False


def fake_migration():
    """Mark the migration as applied without running it"""
    print_section("Marking Migration as Applied")
    
    try:
        # Check if migration already recorded
        with connection.cursor() as cursor:
            cursor.execute("""
                SELECT COUNT(*) FROM django_migrations 
                WHERE app = 'users' 
                AND name = '0023_add_client_approval_fields'
            """)
            exists = cursor.fetchone()[0] > 0
            
            if not exists:
                # Insert into django_migrations to mark as applied
                cursor.execute("""
                    INSERT INTO django_migrations (app, name, applied)
                    VALUES ('users', '0023_add_client_approval_fields', NOW())
                """)
                print("[OK] Migration recorded in django_migrations")
            else:
                print("[OK] Migration already recorded")
        
        return True
    except Exception as e:
        print(f"[FAIL] Failed to record migration: {e}")
        return False


def deploy_migration():
    """Try to deploy using Django migration system"""
    print_section("Deploying via Django Migrations")
    
    try:
        # Try to apply the migration
        call_command('migrate', 'users', verbosity=2)
        print("\n[OK] Migration deployed successfully")
        return True
    except Exception as e:
        print(f"\n[FAIL] Migration failed: {e}")
        print("\nTrying alternative deployment method...")
        return False


def main():
    """Main deployment function"""
    print("\n" + "#" * 80)
    print("#" + " " * 78 + "#")
    print("#  CLIENT APPROVAL SYSTEM - CPANEL PRODUCTION DEPLOYMENT")
    print("#" + " " * 78 + "#")
    print("#" * 80 + "\n")
    
    # Check existing fields
    existing_fields, missing_fields = check_approval_fields()
    
    if len(missing_fields) == 0:
        print_section("Deployment Summary")
        print("[OK] All approval fields already exist in database")
        print("[OK] No deployment needed")
        return 0
    
    print(f"\nNeed to add {len(missing_fields)} field(s)")
    
    # Try Django migration first
    if deploy_migration():
        return 0
    
    # If migration fails, use direct SQL
    print("\n[WARNING] Using direct SQL deployment method")
    if deploy_sql_directly():
        # Record the migration
        fake_migration()
        print_section("Deployment Summary")
        print("[OK] APPROVAL SYSTEM DEPLOYED SUCCESSFULLY")
        print("\nNext steps:")
        print("  1. Clear browser cache")
        print("  2. Test the pending clients page")
        print("  3. Test approve/reject functionality")
        return 0
    else:
        print_section("Deployment Summary")
        print("[FAIL] DEPLOYMENT FAILED")
        return 1


if __name__ == '__main__':
    try:
        exit_code = main()
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n\n[FAIL] Deployment interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n[FAIL] Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

