﻿#!/usr/bin/env python3
"""
Emergency Collation Fix - Quick and Simple
Run this immediately to fix the collation issues
"""

import os
import django
from django.db import connection

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

def fix_collations():
    """Quick fix for collation issues"""
    print("Starting emergency collation fix...")
    
    fixes = [
        # Set database default
        "ALTER DATABASE xygbfpsg_graz CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
        
        # Create missing table
        """CREATE TABLE IF NOT EXISTS `portfolio_performance` (
            `id` bigint NOT NULL AUTO_INCREMENT,
            `date` date NOT NULL,
            `total_loans` int DEFAULT 0,
            `active_loans` int DEFAULT 0,
            `overdue_loans` int DEFAULT 0,
            `total_amount` decimal(15,2) DEFAULT 0.00,
            `collected_amount` decimal(15,2) DEFAULT 0.00,
            `outstanding_amount` decimal(15,2) DEFAULT 0.00,
            `created_at` datetime(6) NOT NULL,
            `updated_at` datetime(6) NOT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `date` (`date`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci""",
        
        # Fix common tables
        "ALTER TABLE auth_user CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
        "ALTER TABLE users_customuser CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
        "ALTER TABLE loans_loan CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
        "ALTER TABLE loans_loanapplication CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
        "ALTER TABLE loans_repayment CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
        "ALTER TABLE utils_receipt CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
        "ALTER TABLE utils_notification CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
    ]
    
    success_count = 0
    error_count = 0
    
    with connection.cursor() as cursor:
        for i, sql in enumerate(fixes, 1):
            try:
                print(f"Executing fix {i}/{len(fixes)}...")
                cursor.execute(sql)
                print(f"✓ Fix {i} completed")
                success_count += 1
            except Exception as e:
                print(f"✗ Fix {i} failed: {str(e)}")
                error_count += 1
                # Continue with other fixes
    
    print(f"\nEmergency fix completed!")
    print(f"Successful: {success_count}")
    print(f"Errors: {error_count}")
    
    if error_count == 0:
        print("✓ All fixes applied successfully!")
    else:
        print("⚠ Some fixes had errors, but the main issues should be resolved")

if __name__ == "__main__":
    fix_collations()