#!/usr/bin/env python
"""
Fix Database Fields (Corrected) Script
This script adds missing fields to M-Pesa related tables using correct table names.
"""
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 find_table_name(pattern):
    """Find table name by pattern"""
    try:
        with connection.cursor() as cursor:
            cursor.execute("""
                SELECT TABLE_NAME 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = DATABASE()
                AND TABLE_NAME LIKE %s
            """, [f'%{pattern}%'])
            tables = [row[0] for row in cursor.fetchall()]
            return tables[0] if tables else None
    except Exception as e:
        print(f"❌ Error finding table {pattern}: {str(e)}")
        return None

def add_repayment_fields():
    """Add missing fields to Repayment model"""
    print("🔄 Adding Repayment model fields...")
    
    # Find the correct repayment table name
    repayment_table = find_table_name('repayment')
    if not repayment_table:
        print("❌ No repayment table found")
        return False
    
    print(f"✅ Found repayment table: {repayment_table}")
    
    try:
        with connection.cursor() as cursor:
            # Check existing fields
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = %s
            """, [repayment_table])
            existing_fields = [row[0] for row in cursor.fetchall()]
            
            # Add payment_source field if missing
            if 'payment_source' not in existing_fields:
                cursor.execute(f"ALTER TABLE {repayment_table} 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 add_mpesa_transaction_fields():
    """Add missing fields to MpesaTransaction model"""
    print("🔄 Adding MpesaTransaction model fields...")
    
    # Find the correct mpesa transaction table name
    mpesa_table = find_table_name('mpesatransaction')
    if not mpesa_table:
        print("❌ No MpesaTransaction table found")
        return False
    
    print(f"✅ Found MpesaTransaction table: {mpesa_table}")
    
    try:
        with connection.cursor() as cursor:
            # Check existing fields
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = %s
            """, [mpesa_table])
            existing_fields = [row[0] for row in cursor.fetchall()]
            
            # 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'),
            ]
            
            for field_name, field_type in fields_to_add:
                if field_name not in existing_fields:
                    try:
                        cursor.execute(f"ALTER TABLE {mpesa_table} 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 MpesaConfiguration model"""
    print("🔄 Adding MpesaConfiguration model fields...")
    
    # Find the correct mpesa configuration table name
    config_table = find_table_name('mpesaconfiguration')
    if not config_table:
        print("❌ No MpesaConfiguration table found")
        return False
    
    print(f"✅ Found MpesaConfiguration table: {config_table}")
    
    try:
        with connection.cursor() as cursor:
            # Check existing fields
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = %s
            """, [config_table])
            existing_fields = [row[0] for row in cursor.fetchall()]
            
            print(f"✅ MpesaConfiguration table exists with {len(existing_fields)} fields")
            return True
            
    except Exception as e:
        print(f"❌ Failed to add MpesaConfiguration fields: {str(e)}")
        return False

def fix_database_fields_corrected():
    """Fix all database fields using correct table names"""
    print("🔧 Fixing Database Fields (Corrected)")
    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...")
    
    print("\n✅ Database fields fix completed!")
    return True

if __name__ == "__main__":
    print("Fix Database Fields (Corrected) Script")
    print("This script adds missing fields using correct table names")
    
    success = fix_database_fields_corrected()
    
    if success:
        print("\n🎉 Database fields 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 database fields!")
        sys.exit(1)
