#!/usr/bin/env python
"""
Verify complete Django setup
"""
import os
import django

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

from django.db import connection
from django.core.management import call_command
import io
import sys

print("=" * 60)
print("DJANGO SETUP VERIFICATION")
print("=" * 60)

# 1. Check migrations
print("\n1. Checking migrations...")
try:
    output = io.StringIO()
    call_command('showmigrations', '--plan', stdout=output)
    migrations_output = output.getvalue()
    applied = migrations_output.count('[X]')
    unapplied = migrations_output.count('[ ]')
    print(f"   ✓ Applied: {applied} migrations")
    if unapplied > 0:
        print(f"   ⚠ Unapplied: {unapplied} migrations")
    else:
        print(f"   ✓ All migrations applied")
except Exception as e:
    print(f"   ✗ Error: {e}")

# 2. Check database tables
print("\n2. Checking database tables...")
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    tables = [table[0] for table in cursor.fetchall()]
    print(f"   ✓ Total tables: {len(tables)}")
    
    # Check critical tables
    critical_tables = [
        'django_migrations',
        'django_content_type',
        'auth_permission',
        'utils_systemsetting',
        'utils_notification',
        'loans',
        'expenses',
    ]
    
    missing = []
    for table in critical_tables:
        if table in tables:
            print(f"   ✓ {table}")
        else:
            print(f"   ✗ {table} MISSING")
            missing.append(table)
    
    if missing:
        print(f"\n   ⚠ Missing {len(missing)} critical tables")
    else:
        print(f"\n   ✓ All critical tables exist")

# 3. Check AUTO_INCREMENT
print("\n3. Checking AUTO_INCREMENT on ID columns...")
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    tables = [table[0] for table in cursor.fetchall()]
    
    issues = []
    for table in tables[:10]:  # Check first 10 tables
        cursor.execute(f"DESCRIBE `{table}`")
        columns = cursor.fetchall()
        for col in columns:
            if col[0] == 'id':
                if 'auto_increment' not in col[5].lower():
                    issues.append(table)
                break
    
    if issues:
        print(f"   ⚠ {len(issues)} tables need AUTO_INCREMENT")
    else:
        print(f"   ✓ AUTO_INCREMENT configured correctly")

# 4. Check system settings
print("\n4. Checking system configuration...")
try:
    from utils.models import SystemSetting
    count = SystemSetting.objects.count()
    print(f"   ✓ SystemSetting model accessible ({count} settings)")
except Exception as e:
    print(f"   ⚠ SystemSetting issue: {e}")

# 5. Summary
print("\n" + "=" * 60)
print("VERIFICATION COMPLETE")
print("=" * 60)
print("\n✓ Django application is ready!")
print("\nTo start the server:")
print("  python manage.py runserver")
print("\nTo access the application:")
print("  http://127.0.0.1:8000/")
print("=" * 60)
