#!/usr/bin/env python
"""
Fix M-Pesa Tables Script
This script adds missing fields to the actual M-Pesa tables found in the database.
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection

def add_mpesa_transaction_fields():
    """Add missing fields to mpesa_transactions table"""
    print("🔄 Adding MpesaTransaction model fields...")
    
    try:
        with connection.cursor() as cursor:
            # Check existing fields in mpesa_transactions table
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'mpesa_transactions'
            """)
            existing_fields = [row[0] for row in cursor.fetchall()]
            
            print(f"Existing fields in mpesa_transactions: {existing_fields}")
            
            # Add missing fields
            fields_to_add = [
                ('trans_id', 'VARCHAR(50) NULL'),
                ('transaction_type', 'VARCHAR(20) DEFAULT "c2b"'),
                ('amount', 'DECIMAL(10,2) NULL'),
                ('phone_number', 'VARCHAR(20) NULL'),
                ('trans_time', 'VARCHAR(20) NULL'),
                ('business_short_code', 'VARCHAR(10) NULL'),
                ('bill_ref_number', 'VARCHAR(50) NULL'),
                ('invoice_number', 'VARCHAR(50) NULL'),
                ('org_account_balance', 'DECIMAL(10,2) NULL'),
                ('third_party_trans_id', 'VARCHAR(50) NULL'),
                ('msisdn', 'VARCHAR(20) NULL'),
                ('first_name', 'VARCHAR(100) NULL'),
                ('middle_name', 'VARCHAR(100) NULL'),
                ('last_name', 'VARCHAR(100) NULL'),
                ('status', 'VARCHAR(20) DEFAULT "pending"'),
                ('raw_confirmation_data', 'JSON NULL'),
                ('is_automatic', 'BOOLEAN DEFAULT TRUE'),
                ('payment_source', 'VARCHAR(20) DEFAULT "automatic"'),
                ('merchant_request_id', 'VARCHAR(50) NULL'),
                ('checkout_request_id', 'VARCHAR(50) NULL'),
                ('processing_notes', 'TEXT NULL'),
                ('borrower_id', 'VARCHAR(36) NULL'),
                ('loan_id', 'VARCHAR(36) NULL'),
                ('processed_at', 'DATETIME NULL'),
                ('created_at', 'DATETIME DEFAULT CURRENT_TIMESTAMP'),
                ('updated_at', 'DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
            ]
            
            for field_name, field_type in fields_to_add:
                if field_name not in existing_fields:
                    try:
                        cursor.execute(f"ALTER TABLE mpesa_transactions ADD COLUMN {field_name} {field_type}")
                        print(f"✅ Added field: {field_name}")
                    except Exception as e:
                        if "Duplicate column name" in str(e):
                            print(f"✅ Field already exists: {field_name}")
                        else:
                            print(f"❌ Failed to add field {field_name}: {str(e)}")
                            return False
                else:
                    print(f"✅ Field already exists: {field_name}")
            
            return True
            
    except Exception as e:
        print(f"❌ Failed to add MpesaTransaction fields: {str(e)}")
        return False

def add_mpesa_configuration_fields():
    """Add missing fields to mpesa_configurations table"""
    print("🔄 Adding MpesaConfiguration model fields...")
    
    try:
        with connection.cursor() as cursor:
            # Check existing fields in mpesa_configurations table
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'mpesa_configurations'
            """)
            existing_fields = [row[0] for row in cursor.fetchall()]
            
            print(f"Existing fields in mpesa_configurations: {existing_fields}")
            
            # Add missing fields if needed
            fields_to_add = [
                ('validation_url', 'VARCHAR(255) NULL'),
                ('confirmation_url', 'VARCHAR(255) NULL'),
                ('response_type', 'VARCHAR(20) DEFAULT "Completed"'),
                ('is_active', 'BOOLEAN DEFAULT TRUE'),
            ]
            
            for field_name, field_type in fields_to_add:
                if field_name not in existing_fields:
                    try:
                        cursor.execute(f"ALTER TABLE mpesa_configurations ADD COLUMN {field_name} {field_type}")
                        print(f"✅ Added field: {field_name}")
                    except Exception as e:
                        if "Duplicate column name" in str(e):
                            print(f"✅ Field already exists: {field_name}")
                        else:
                            print(f"❌ Failed to add field {field_name}: {str(e)}")
                            return False
                else:
                    print(f"✅ Field already exists: {field_name}")
            
            return True
            
    except Exception as e:
        print(f"❌ Failed to add MpesaConfiguration fields: {str(e)}")
        return False

def add_repayment_fields():
    """Add missing fields to repayments table"""
    print("🔄 Adding Repayment model fields...")
    
    try:
        with connection.cursor() as cursor:
            # Check existing fields in repayments table
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'repayments'
            """)
            existing_fields = [row[0] for row in cursor.fetchall()]
            
            print(f"Existing fields in repayments: {existing_fields}")
            
            # Add payment_source field if missing
            if 'payment_source' not in existing_fields:
                cursor.execute("ALTER TABLE repayments ADD COLUMN payment_source VARCHAR(20) DEFAULT 'manual'")
                print("✅ Added payment_source field to Repayment model")
            else:
                print("✅ payment_source field already exists in Repayment model")
            
            return True
            
    except Exception as e:
        print(f"❌ Failed to add Repayment fields: {str(e)}")
        return False

def test_mpesa_models():
    """Test M-Pesa models after adding fields"""
    print("\n🔄 Testing M-Pesa models...")
    
    try:
        # Test MpesaTransaction model
        from loans.models import MpesaTransaction
        
        # Try to query the model
        count = MpesaTransaction.objects.count()
        print(f"✅ MpesaTransaction model working - {count} records found")
        
        # Test MpesaConfiguration model
        from payments.models import MpesaConfiguration
        
        # Try to query the model
        count = MpesaConfiguration.objects.count()
        print(f"✅ MpesaConfiguration model working - {count} records found")
        
        return True
        
    except Exception as e:
        print(f"❌ M-Pesa models test failed: {str(e)}")
        return False

def fix_mpesa_tables():
    """Fix all M-Pesa tables"""
    print("🔧 Fixing M-Pesa Tables")
    print("=" * 50)
    
    # Fix Repayment model
    if not add_repayment_fields():
        print("⚠️ Repayment fields fix failed, continuing...")
    
    # Fix MpesaTransaction model
    if not add_mpesa_transaction_fields():
        print("⚠️ MpesaTransaction fields fix failed, continuing...")
    
    # Fix MpesaConfiguration model
    if not add_mpesa_configuration_fields():
        print("⚠️ MpesaConfiguration fields fix failed, continuing...")
    
    # Test models
    if test_mpesa_models():
        print("\n✅ All M-Pesa models are working!")
    else:
        print("\n⚠️ Some M-Pesa models may have issues")
    
    print("\n✅ M-Pesa tables fix completed!")
    return True

if __name__ == "__main__":
    print("Fix M-Pesa Tables Script")
    print("This script adds missing fields to the actual M-Pesa tables")
    
    success = fix_mpesa_tables()
    
    if success:
        print("\n🎉 M-Pesa tables fix completed!")
        print("\n📋 Next Steps:")
        print("1. Try accessing the payments dashboard again")
        print("2. Test M-Pesa integration")
        print("3. Check that all models are working")
    else:
        print("\n❌ Failed to fix M-Pesa tables!")
        sys.exit(1)
