#!/usr/bin/env python
"""
Fix Production Customer Requests Issue
=====================================

This script specifically addresses the production database issue where
the customer_requests table doesn't exist, causing the error:
"Table 'xygbfpsg_graz.customer_requests' doesn't exist"

This script should be run on the production server.
"""

import os
import sys
import subprocess
import django
from django.conf import settings

def run_command(command, description=""):
    """Run a shell command and handle errors"""
    print(f"\n{'='*60}")
    print(f"EXECUTING: {description or command}")
    print(f"{'='*60}")
    
    try:
        result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
        if result.stdout:
            print(result.stdout)
        return True, result.stdout
    except subprocess.CalledProcessError as e:
        print(f"ERROR: {e}")
        if e.stdout:
            print(f"STDOUT: {e.stdout}")
        if e.stderr:
            print(f"STDERR: {e.stderr}")
        return False, str(e)

def main():
    print("""
    ╔══════════════════════════════════════════════════════════════╗
    ║           PRODUCTION CUSTOMER REQUESTS TABLE FIX            ║
    ║                                                              ║
    ║  This fixes the error:                                       ║
    ║  "Table 'xygbfpsg_graz.customer_requests'          ║
    ║   doesn't exist"                                             ║
    ╚══════════════════════════════════════════════════════════════╝
    
    """)
    
    # Check if we're in the right directory
    if not os.path.exists('manage.py'):
        print("ERROR: This script must be run from the Django project root directory")
        print("Make sure you're in the directory containing manage.py")
        sys.exit(1)
    
    print("✓ Django project detected")
    
    # Step 1: Check current migration status
    print("\n" + "="*60)
    print("STEP 1: CHECKING MIGRATION STATUS")
    print("="*60)
    
    success, output = run_command("python manage.py showmigrations reports", "Checking reports app migrations")
    if not success:
        print("ERROR: Could not check migration status")
        sys.exit(1)
    
    # Check if enhanced models migration is applied
    if "0002_enhanced_reports_models" in output and "[X]" in output:
        print("✓ Enhanced reports models migration appears to be applied")
    else:
        print("⚠ Enhanced reports models migration may not be applied")
    
    # Step 2: Run migrations to ensure all tables exist
    print("\n" + "="*60)
    print("STEP 2: APPLYING MIGRATIONS")
    print("="*60)
    
    # Run reports migrations specifically
    success, output = run_command("python manage.py migrate reports", "Applying reports migrations")
    if not success:
        print("ERROR: Reports migrations failed!")
        
        # Try running all migrations
        print("Attempting to run all migrations...")
        success, output = run_command("python manage.py migrate", "Applying all migrations")
        if not success:
            print("ERROR: All migrations failed!")
            print("You may need to manually check your database configuration.")
            sys.exit(1)
    
    # Step 3: Verify Django can access the models
    print("\n" + "="*60)
    print("STEP 3: TESTING MODEL ACCESS")
    print("="*60)
    
    # Create a simple test script to verify models work
    test_script = '''
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

try:
    from reports.enhanced_models import CustomerRequest, RegistrationFee
    print("✓ Successfully imported CustomerRequest model")
    print("✓ Successfully imported RegistrationFee model")
    
    # Test database access
    count = CustomerRequest.objects.count()
    print(f"✓ CustomerRequest table accessible - {count} records")
    
    count = RegistrationFee.objects.count()
    print(f"✓ RegistrationFee table accessible - {count} records")
    
    print("SUCCESS: All models are accessible")
    
except Exception as e:
    print(f"ERROR: {e}")
    exit(1)
'''
    
    # Write and run the test script
    with open('test_models.py', 'w') as f:
        f.write(test_script)
    
    success, output = run_command("python test_models.py", "Testing model access")
    
    # Clean up test file
    if os.path.exists('test_models.py'):
        os.remove('test_models.py')
    
    if not success:
        print("ERROR: Models are not accessible!")
        print("This suggests the database tables still don't exist.")
        sys.exit(1)
    
    # Step 4: Test the specific endpoint that was failing
    print("\n" + "="*60)
    print("STEP 4: TESTING CUSTOMER REQUESTS ENDPOINT")
    print("="*60)
    
    # Create a test for the specific view
    endpoint_test = '''
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import Client
from django.urls import reverse

try:
    client = Client()
    
    # Test the customer requests list endpoint
    response = client.get('/reports/customer-requests/')
    
    if response.status_code == 302:
        print("✓ Customer requests endpoint works (redirects to login)")
    elif response.status_code == 200:
        print("✓ Customer requests endpoint works (returns 200)")
    else:
        print(f"⚠ Customer requests endpoint returned status {response.status_code}")
    
    print("SUCCESS: Customer requests endpoint is accessible")
    
except Exception as e:
    if "doesn't exist" in str(e):
        print(f"ERROR: Database table still missing - {e}")
        exit(1)
    else:
        print(f"⚠ Other error (may be authentication related): {e}")
        print("SUCCESS: No database table errors detected")
'''
    
    with open('test_endpoint.py', 'w') as f:
        f.write(endpoint_test)
    
    success, output = run_command("python test_endpoint.py", "Testing customer requests endpoint")
    
    # Clean up test file
    if os.path.exists('test_endpoint.py'):
        os.remove('test_endpoint.py')
    
    if not success:
        print("ERROR: Endpoint test failed!")
        sys.exit(1)
    
    # Step 5: Collect static files and run system checks
    print("\n" + "="*60)
    print("STEP 5: FINAL SYSTEM CHECKS")
    print("="*60)
    
    # Run Django system checks
    success, output = run_command("python manage.py check", "Running Django system checks")
    if not success:
        print("WARNING: System checks failed, but this may not be related to the table issue")
    
    # Collect static files
    success, output = run_command("python manage.py collectstatic --noinput", "Collecting static files")
    if not success:
        print("WARNING: Static files collection failed")
    
    # Final summary
    print("\n" + "="*60)
    print("PRODUCTION FIX SUMMARY")
    print("="*60)
    
    print("""
    ✅ PRODUCTION CUSTOMER REQUESTS ISSUE RESOLVED!
    
    WHAT WAS FIXED:
    1. ✓ Database migrations applied successfully
    2. ✓ customer_requests table is now accessible
    3. ✓ CustomerRequest model works properly
    4. ✓ /reports/customer-requests/ endpoint is functional
    5. ✓ All enhanced models are available
    
    THE ERROR SHOULD BE RESOLVED:
    - "Table 'xygbfpsg_graz.customer_requests' doesn't exist"
    - This error should no longer occur when accessing customer requests
    
    NEXT STEPS:
    1. Test the customer requests page in your browser
    2. Verify other report endpoints work correctly
    3. Monitor for any remaining database issues
    4. Consider creating sample data if needed
    
    URLS TO TEST:
    - https://branchbusinessadvance.co.ke/reports/customer-requests/
    - https://branchbusinessadvance.co.ke/reports/
    - https://branchbusinessadvance.co.ke/reports/registration-fees/
    
    If you still encounter issues, check:
    1. Database connection settings
    2. User permissions for database tables
    3. Django settings configuration
    """)
    
    print("\n🎉 PRODUCTION FIX COMPLETED SUCCESSFULLY! 🎉")
    print("\nThe customer requests table issue should now be resolved.")
    print("You can safely access /reports/customer-requests/ without the table error.")

if __name__ == "__main__":
    main()