#!/usr/bin/env python3
"""
Fix final setup issues
"""

import os
import sys
import django
from django.db import connection

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
django.setup()

def fix_migration_issue():
    """Fix the migration dependency issue"""
    print("🔧 Fixing migration dependency issue...")
    
    try:
        with connection.cursor() as cursor:
            # Add the missing migration to the database
            cursor.execute("""
                INSERT IGNORE INTO django_migrations (app, name, applied) 
                VALUES ('loans', '0014_merge_20250827_0154', NOW())
            """)
            print("✅ SUCCESS: Added missing migration to database")
            
    except Exception as e:
        print(f"❌ ERROR: {e}")

def test_loan_products():
    """Test creating loan products"""
    print("🏦 Testing loan product creation...")
    
    try:
        from loans.models import LoanProduct
        from decimal import Decimal
        
        # Test creating one product
        product_data = {
            'name': 'Boost',
            'product_type': 'boost',
            'description': 'Quick short-term loans for immediate business needs',
            'min_amount': Decimal('1000.00'),
            'max_amount': Decimal('50000.00'),
            'interest_rate': Decimal('15.00'),
            'processing_fee': Decimal('3.00'),
            'duration_months': 1,
            'min_duration': 7,
            'max_duration': 30,
            'is_active': True,
            'requires_collateral': False,
            'available_durations': [7, 14, 30],
            'available_repayment_methods': ['daily', 'weekly', 'monthly'],
        }
        
        product, created = LoanProduct.objects.get_or_create(
            name=product_data['name'],
            defaults=product_data
        )
        
        if created:
            print("✅ SUCCESS: Created test loan product")
        else:
            print("✅ SUCCESS: Test loan product already exists")
            
        print(f"Product: {product.name} - {product.product_type}")
        
    except Exception as e:
        print(f"❌ ERROR: {e}")

def test_admin_user():
    """Test admin user login"""
    print("👤 Testing admin user...")
    
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        user = User.objects.get(email='admin@branchbusinessadvance.com')
        print(f"✅ SUCCESS: Admin user exists - {user.email}")
        print(f"   Role: {user.role}")
        print(f"   Status: {user.status}")
        print(f"   Is Staff: {user.is_staff}")
        print(f"   Is Superuser: {user.is_superuser}")
        
    except Exception as e:
        print(f"❌ ERROR: {e}")

if __name__ == "__main__":
    print("🚀 Running final fixes...")
    fix_migration_issue()
    test_loan_products()
    test_admin_user()
    print("🎉 Final fixes completed!")