#!/usr/bin/env python
"""
Fix migration state by marking existing migrations as applied
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.core.management import call_command
from django.db import connection

print("Fixing migration state...")
print("=" * 60)

# Get list of all apps with migrations
apps = ['contenttypes', 'auth', 'admin', 'sessions', 'users', 'loans', 'payments', 'reports', 'utils', 'expenses']

# Check which tables exist
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    existing_tables = [table[0] for table in cursor.fetchall()]
    print(f"\nFound {len(existing_tables)} existing tables in database")

# Fake all migrations for apps that have tables
print("\nFaking migrations for existing tables...")
for app in apps:
    try:
        print(f"\n{app}:")
        call_command('migrate', app, '--fake', verbosity=1)
        print(f"  ✓ Migrations faked successfully")
    except Exception as e:
        print(f"  ⚠ Warning: {e}")

print("\n" + "=" * 60)
print("Migration state fixed!")
print("\nNow run: python manage.py migrate")
