#!/usr/bin/env python
"""
Quick script to populate sample data using raw SQL where needed
"""
import os
import sys
import django
from datetime import datetime, timedelta
from decimal import Decimal
import random

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.contrib.auth import get_user_model
from users.models import Branch
from loans.models import Loan, Repayment
from expenses.models import Expense
from django.utils import timezone
from django.db import connection

User = get_user_model()

print("=" * 60)
print("QUICK DATA POPULATION")
print("=" * 60)

# Check existing data
print(f"\nCurrent data:")
print(f"  Branches: {Branch.objects.count()}")
print(f"  Users: {User.objects.count()}")
print(f"  Borrowers: {User.objects.filter(role='borrower').count()}")
print(f"  Loans: {Loan.objects.count()}")
print(f"  Expenses: {Expense.objects.count()}")

# Create loan products using raw SQL to avoid UUID issues
print("\n" + "=" * 60)
print("Creating loan products...")
print("=" * 60)

with connection.cursor() as cursor:
    # Check if products exist
    cursor.execute("SELECT COUNT(*) FROM loan_products")
    count = cursor.fetchone()[0]
    
    if count == 0:
        products_sql = [
            ("INSERT INTO loan_products (name, product_type, description, min_amount, max_amount, "
             "interest_rate, processing_fee, late_payment_penalty, duration_months, min_duration, "
             "max_duration, available_durations, available_repayment_methods, requires_guarantor, "
             "requires_collateral, rollover_fee_percentage, max_rollover_count, max_rollover_days, "
             "is_active, created_at, updated_at) VALUES "
             "('Mwamba', 'mwamba', 'Short-term business loan', 5000, 50000, 20.00, 10.00, 5.00, "
             "1, 30, 30, '[]', '[\"monthly\"]', 0, 0, 5.00, 3, 30, 1, NOW(), NOW())"),
            
            ("INSERT INTO loan_products (name, product_type, description, min_amount, max_amount, "
             "interest_rate, processing_fee, late_payment_penalty, duration_months, min_duration, "
             "max_duration, available_durations, available_repayment_methods, requires_guarantor, "
             "requires_collateral, rollover_fee_percentage, max_rollover_count, max_rollover_days, "
             "is_active, created_at, updated_at) VALUES "
             "('Boost Plus', 'boost_plus', 'Medium-term growth loan', 10000, 100000, 15.00, 8.00, 5.00, "
             "3, 30, 90, '[30, 60, 90]', '[\"monthly\"]', 0, 0, 5.00, 3, 30, 1, NOW(), NOW())"),
            
            ("INSERT INTO loan_products (name, product_type, description, min_amount, max_amount, "
             "interest_rate, processing_fee, late_payment_penalty, duration_months, min_duration, "
             "max_duration, available_durations, available_repayment_methods, requires_guarantor, "
             "requires_collateral, rollover_fee_percentage, max_rollover_count, max_rollover_days, "
             "is_active, created_at, updated_at) VALUES "
             "('Boost', 'boost', 'Long-term business expansion', 20000, 200000, 12.00, 5.00, 5.00, "
             "6, 90, 180, '[]', '[\"monthly\"]', 0, 0, 5.00, 3, 30, 1, NOW(), NOW())"),
        ]
        
        for sql in products_sql:
            try:
                cursor.execute(sql)
                print(f"  ✓ Created loan product")
            except Exception as e:
                print(f"  ✗ Error: {e}")
        
        cursor.execute("SELECT COUNT(*) FROM loan_products")
        count = cursor.fetchone()[0]
        print(f"\n✓ Total loan products: {count}")
    else:
        print(f"  ℹ {count} loan products already exist")

print("\n" + "=" * 60)
print("FINAL SUMMARY")
print("=" * 60)
print(f"Branches: {Branch.objects.count()}")
print(f"Users: {User.objects.count()}")
print(f"  - Admins: {User.objects.filter(role='admin').count()}")
print(f"  - Branch Managers: {User.objects.filter(role='branch_manager').count()}")  
print(f"  - Loan Officers: {User.objects.filter(role='loan_officer').count()}")
print(f"  - Borrowers: {User.objects.filter(role='borrower').count()}")

with connection.cursor() as cursor:
    cursor.execute("SELECT COUNT(*) FROM loan_products")
    print(f"Loan Products: {cursor.fetchone()[0]}")

print(f"Loans: {Loan.objects.count()}")
print(f"Expenses: {Expense.objects.count()}")

print("\n" + "=" * 60)
print("✓ Data population completed!")
print("=" * 60)

print("\nLOGIN CREDENTIALS:")
print("-" * 60)
print("Admin: admin / admin (check existing admin user)")
print("Manager: manager1@branch.com / manager123")
print("Loan Officer: officer1@branch.com / officer123")
print("Borrower: borrower1@example.com / borrower123")
print("-" * 60)
