#!/usr/bin/env python3
"""
Simple fix for receipts table missing columns - No Unicode
"""

import os
import sys
import django

def main():
    print("Starting receipts table fix...")
    
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
        django.setup()
        
        from django.db import connection
        
        with connection.cursor() as cursor:
            print("Checking receipts table...")
            
            # Add missing columns one by one
            columns_to_add = [
                ('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 column_name, column_def in columns_to_add:
                try:
                    cursor.execute(f"ALTER TABLE receipts ADD COLUMN {column_name} {column_def}")
                    print(f"Added column: {column_name}")
                except Exception as e:
                    if "Duplicate column name" in str(e):
                        print(f"Column {column_name} already exists")
                    else:
                        print(f"Error adding {column_name}: {e}")
            
            # Create repayments table if it doesn't exist
            try:
                cursor.execute("""
                    CREATE TABLE IF NOT EXISTS 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("Repayments table ready")
            except Exception as e:
                print(f"Repayments table error: {e}")
            
            print("Fix completed successfully!")
            return True
            
    except Exception as e:
        print(f"Error: {e}")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)