﻿#!/usr/bin/env python
"""
Sync migration state with production database
"""

import os
import sys
import django
from pathlib import Path

# Set production database credentials
os.environ['DB_NAME'] = 'xygbfpsg_graz'
os.environ['DB_USER'] = 'xygbfpsg_graz'
os.environ['DB_PASSWORD'] = ',qdN3O_!}oC67(]W'
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_PORT'] = '3306'

# Setup Django
BASE_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(BASE_DIR))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.core.management import call_command
from django.db import connection

print("="*60)
print("SYNCING MIGRATION STATE")
print("="*60)

# Step 1: Check what tables exist
print("\n[1/3] Checking existing tables...")
with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES")
    existing_tables = [row[0] for row in cursor.fetchall()]
    print(f"✓ Found {len(existing_tables)} tables")

# Step 2: Fake migrations for tables that already exist
print("\n[2/3] Marking existing migrations as applied...")
apps_to_fake = ['admin', 'auth', 'contenttypes', 'sessions']

for app in apps_to_fake:
    try:
        call_command('migrate', app, '--fake', verbosity=0)
        print(f"  ✓ {app}")
    except Exception as e:
        print(f"  ⚠ {app}: {e}")

# Step 3: Apply remaining migrations
print("\n[3/3] Applying new migrations...")
try:
    call_command('migrate', '--noinput', verbosity=1)
    print("✓ Migrations applied")
except Exception as e:
    print(f"⚠ Some migrations may have failed: {e}")
    print("\nTrying to continue anyway...")

print("\n" + "="*60)
print("✅ MIGRATION SYNC COMPLETED")
print("="*60)
print("\nThe client performance page should now work!")
print("Refresh the page to see the data.")
