#!/usr/bin/env python
"""
Create accounting tables directly using Django's schema editor
This bypasses migration issues
"""

import os
import sys
from pathlib import Path

print("=" * 60)
print("Creating Accounting Tables")
print("=" * 60)
print()

# Load .env
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / '.env', override=True)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
os.environ['DB_USER'] = os.getenv('DB_USER', 'xygbfpsg_graz')
os.environ['DB_PASSWORD'] = os.getenv('DB_PASSWORD', '')
os.environ['DB_NAME'] = os.getenv('DB_NAME', 'xygbfpsg_loans')

import django
django.setup()

from django.db import connection
from django.core.management import call_command

print("[1/2] Creating accounting tables...")

try:
    # Use Django's migrate command with --run-syncdb to create tables
    call_command('migrate', 'accounting', run_syncdb=True, verbosity=2)
    print("  ✓ Tables created")
except Exception as e:
    print(f"  Error: {e}")
    print()
    print("  Trying alternative method...")
    
    # Alternative: Use schema editor directly
    from django.db import connection
    from accounting.models import Account, JournalEntry, JournalEntryLine, GeneralLedger, FiscalPeriod, AccountBalance
    
    with connection.schema_editor() as schema_editor:
        for model in [Account, FiscalPeriod, JournalEntry, JournalEntryLine, GeneralLedger, AccountBalance]:
            try:
                schema_editor.create_model(model)
                print(f"  ✓ Created table for {model.__name__}")
            except Exception as e:
                if 'already exists' in str(e).lower():
                    print(f"  - Table for {model.__name__} already exists")
                else:
                    print(f"  ✗ Error creating {model.__name__}: {e}")

print()
print("[2/2] Verifying tables...")

with connection.cursor() as cursor:
    cursor.execute("SHOW TABLES LIKE 'accounting_%'")
    tables = cursor.fetchall()
    
    if tables:
        print(f"  ✓ Found {len(tables)} accounting tables:")
        for table in tables:
            print(f"    - {table[0]}")
    else:
        print("  ✗ No accounting tables found")
        sys.exit(1)

print()
print("=" * 60)
print("SUCCESS! Tables created")
print("=" * 60)
print()
print("Now run: python final_deploy.py")
print()
