#!/usr/bin/env python
"""
Non-interactive script to fix production database issues
Run with: python fix_production_database.py
"""

import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

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

def execute_sql(sql, description):
    """Execute SQL and handle errors"""
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
        print(f"✓ {description}")
        return True
    except Exception as e:
        if "Duplicate column" in str(e) or "already exists" in str(e):
            print(f"⊙ {description} (already exists, skipping)")
            return True
        else:
            print(f"✗ {description}: {e}")
            return False

def check_column_exists(table, column):
    """Check if a column exists in a table"""
    with connection.cursor() as cursor:
        cursor.execute(f"""
            SELECT COUNT(*) 
            FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE()
            AND TABLE_NAME = '{table}'
            AND COLUMN_NAME = '{column}'
        """)
        return cursor.fetchone()[0] > 0

def main():
    print("=" * 70)
    print("Production Database Fix Script")
    print("=" * 70)
    print()
    
    # 1. Add business_short_code column to mpesa_transactions
    print("Step 1: Adding business_short_code column to mpesa_transactions...")
    if not check_column_exists('mpesa_transactions', 'business_short_code'):
        execute_sql(
            "ALTER TABLE mpesa_transactions ADD COLUMN business_short_code VARCHAR(10) NULL",
            "Added business_short_code column"
        )
    else:
        print("⊙ business_short_code column already exists")
    
    print()
    
    # 2. Add approval fields to users_customuser if missing
    print("Step 2: Adding approval fields to users_customuser...")
    
    approval_fields = [
        ('approval_reason', 'TEXT'),
        ('approved_at', 'DATETIME'),
        ('approved_by_id', 'CHAR(32)'),
        ('rejected_at', 'DATETIME'),
        ('rejected_by_id', 'CHAR(32)'),
        ('rejection_reason', 'TEXT'),
    ]
    
    for field_name, field_type in approval_fields:
        if not check_column_exists('users_customuser', field_name):
            execute_sql(
                f"ALTER TABLE users_customuser ADD COLUMN {field_name} {field_type} NULL",
                f"Added {field_name} column"
            )
        else:
            print(f"⊙ {field_name} column already exists")
    
    print()
    
    # 3. Fake migrations that are already applied in production
    print("Step 3: Marking migrations as applied...")
    
    try:
        # Mark loans migration as applied
        call_command('migrate', 'loans', '0021', '--fake', verbosity=0)
        print("✓ Marked loans.0021 as applied")
    except Exception as e:
        print(f"⊙ loans.0021 migration: {e}")
    
    try:
        # Mark users migration as applied
        call_command('migrate', 'users', '0023', '--fake', verbosity=0)
        print("✓ Marked users.0023 as applied")
    except Exception as e:
        print(f"⊙ users.0023 migration: {e}")
    
    try:
        # Apply all remaining migrations
        call_command('migrate', '--fake', verbosity=0)
        print("✓ Marked all remaining migrations as applied")
    except Exception as e:
        print(f"⊙ Remaining migrations: {e}")
    
    print()
    print("=" * 70)
    print("✓ Database fix completed!")
    print("=" * 70)
    print()
    print("Next steps:")
    print("1. Test the unconfirmed payments page: /payments/unconfirmed-payments/")
    print("2. Contact Safaricom to update callback URLs for paybill 4086675")
    print("   - Validation: https://branchbusinessadvance.co.ke/payments/callback/main/validation/")
    print("   - Confirmation: https://branchbusinessadvance.co.ke/payments/callback/main/confirmation/")
    print()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("\n\nScript interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n✗ Fatal error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
