my"""
Diagnose why tables aren't being created
"""
import os
import sys

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import django
django.setup()

from django.db import connection
from django.conf import settings
from django.apps import apps

print("="*60)
print("  DIAGNOSING TABLE ISSUE")
print("="*60)

print("\n1. Check AUTH_USER_MODEL setting...")
print("-"*60)
auth_user_model = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
print(f"AUTH_USER_MODEL: {auth_user_model}")

if auth_user_model != 'users.CustomUser':
    print("❌ AUTH_USER_MODEL is not set to 'users.CustomUser'")
    print("This needs to be fixed in settings.py!")
else:
    print("✅ AUTH_USER_MODEL correctly set")

print("\n2. Check what tables exist...")
print("-"*60)
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    tables = [table[0] for table in cursor.fetchall()]
    
    print(f"Total tables: {len(tables)}")
    
    # Check for user-related tables
    user_tables = [t for t in tables if 'user' in t.lower()]
    print(f"\nUser-related tables:")
    for table in user_tables:
        print(f"  - {table}")
    
    # Check for loan-related tables
    loan_tables = [t for t in tables if 'loan' in t.lower()]
    print(f"\nLoan-related tables:")
    for table in loan_tables:
        print(f"  - {table}")

print("\n3. Check CustomUser model configuration...")
print("-"*60)
try:
    CustomUser = apps.get_model('users', 'CustomUser')
    print(f"✅ CustomUser model found")
    print(f"   Table name: {CustomUser._meta.db_table}")
    print(f"   App label: {CustomUser._meta.app_label}")
    print(f"   Model name: {CustomUser._meta.model_name}")
except Exception as e:
    print(f"❌ CustomUser model error: {e}")

print("\n4. Check Loan model configuration...")
print("-"*60)
try:
    Loan = apps.get_model('loans', 'Loan')
    print(f"✅ Loan model found")
    print(f"   Table name: {Loan._meta.db_table}")
except Exception as e:
    print(f"❌ Loan model error: {e}")

print("\n5. Check Repayment model configuration...")
print("-"*60)
try:
    Repayment = apps.get_model('loans', 'Repayment')
    print(f"✅ Repayment model found")
    print(f"   Table name: {Repayment._meta.db_table}")
except Exception as e:
    print(f"❌ Repayment model error: {e}")

print("\n6. Check migration state...")
print("-"*60)
with connection.cursor() as cursor:
    cursor.execute("""
        SELECT app, name 
        FROM django_migrations 
        WHERE app IN ('users', 'loans')
        ORDER BY id DESC 
        LIMIT 10
    """)
    migrations = cursor.fetchall()
    print("Recent migrations:")
    for app, name in migrations:
        print(f"  {app}: {name}")

print("\n" + "="*60)
print("  DIAGNOSIS COMPLETE")
print("="*60)

print("\nIssues found:")
if auth_user_model != 'users.CustomUser':
    print("1. AUTH_USER_MODEL not set correctly")
    print("   Add to settings.py: AUTH_USER_MODEL = 'users.CustomUser'")

print("\nNext steps:")
print("1. If AUTH_USER_MODEL is wrong, fix it in settings.py")
print("2. Run: python fix_table_names.py")
