#!/usr/bin/env python3
"""
Clean fix for receipts table - Pure ASCII only
"""

import os
import sys
import django

def main():
    print("HAVEN GRAZURI INVESTMENT LIMITED- Receipts Table Fix")
    print("=" * 50)
    
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
        django.setup()
        
        from django.db import connection
        
        print("Django setup completed")
        print("Fixing receipts table...")
        
        with connection.cursor() as cursor:
            # Check if receipts table exists
            cursor.execute("""
                SELECT TABLE_NAME 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'receipts'
            """)
            
            if not cursor.fetchone():
                print("Creating receipts table...")
                cursor.execute("""
                    CREATE TABLE receipts (
                        id CHAR(32) NOT NULL PRIMARY KEY,
                        repayment_id CHAR(32) NULL,
                        loan_id CHAR(32) NOT NULL,
                        borrower_id CHAR(32) NOT NULL,
                        receipt_number VARCHAR(20) NOT NULL UNIQUE,
                        amount_paid DECIMAL(12,2) NOT NULL,
                        payment_method VARCHAR(20) NOT NULL,
                        payment_date DATETIME(6) NOT NULL,
                        previous_balance DECIMAL(12,2) NOT NULL,
                        new_balance DECIMAL(12,2) NOT NULL,
                        pdf_file VARCHAR(100) NULL,
                        created_at DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6)
                    )
                """)
                print("SUCCESS: Created receipts table")
            else:
                print("Receipts table exists, checking columns...")
                
                # Add missing columns
                columns = [
                    ('repayment_id', 'CHAR(32) NULL'),
                    ('loan_id', 'CHAR(32) NULL'),
                    ('borrower_id', 'CHAR(32) NULL'),
                    ('amount_paid', 'DECIMAL(12,2) NULL'),
                    ('payment_method', 'VARCHAR(20) NULL'),
                    ('payment_date', 'DATETIME(6) NULL'),
                    ('previous_balance', 'DECIMAL(12,2) NULL'),
                    ('new_balance', 'DECIMAL(12,2) NULL'),
                    ('pdf_file', 'VARCHAR(100) NULL'),
                    ('created_at', 'DATETIME(6) NULL'),
                ]
                
                for col_name, col_def in columns:
                    try:
                        cursor.execute(f"ALTER TABLE receipts ADD COLUMN {col_name} {col_def}")
                        print(f"SUCCESS: Added {col_name} column")
                    except Exception as e:
                        if "Duplicate column name" in str(e):
                            print(f"OK: Column {col_name} already exists")
                        else:
                            print(f"ERROR: Failed to add {col_name}: {e}")
            
            # Create repayments table if needed
            cursor.execute("""
                SELECT TABLE_NAME 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'repayments'
            """)
            
            if not cursor.fetchone():
                print("Creating repayments table...")
                cursor.execute("""
                    CREATE TABLE repayments (
                        id CHAR(32) NOT NULL PRIMARY KEY,
                        loan_id CHAR(32) NOT NULL,
                        amount DECIMAL(12,2) NOT NULL,
                        payment_method VARCHAR(20) NOT NULL DEFAULT 'mpesa',
                        mpesa_transaction_id VARCHAR(50) NULL,
                        mpesa_phone_number VARCHAR(17) NULL,
                        receipt_number VARCHAR(20) NOT NULL UNIQUE,
                        payment_date DATETIME(6) NOT NULL,
                        created_at DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6)
                    )
                """)
                print("SUCCESS: Created repayments table")
            else:
                print("OK: Repayments table exists")
            
            # Add basic indexes
            indexes = [
                'CREATE INDEX IF NOT EXISTS idx_receipts_loan_id ON receipts (loan_id)',
                'CREATE INDEX IF NOT EXISTS idx_receipts_borrower_id ON receipts (borrower_id)',
                'CREATE INDEX IF NOT EXISTS idx_receipts_repayment_id ON receipts (repayment_id)',
                'CREATE INDEX IF NOT EXISTS idx_repayments_loan_id ON repayments (loan_id)',
            ]
            
            for index_sql in indexes:
                try:
                    cursor.execute(index_sql)
                    print("SUCCESS: Created index")
                except Exception as e:
                    print(f"OK: Index exists or error: {e}")
        
        print("\n" + "=" * 50)
        print("SUCCESS: Fix completed successfully!")
        print("Your loan repayment functionality should now work.")
        print("=" * 50)
        return True
        
    except Exception as e:
        print(f"\nERROR: {e}")
        import traceback
        print(f"Details: {traceback.format_exc()}")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)