#!/usr/bin/env python
"""
Complete Import Process - Import SQL file then migrate all data
"""
import subprocess
import sys
import os

print("=" * 100)
print("HAVEN GRAZURI - COMPLETE DATA IMPORT")
print("=" * 100)

# Step 1: Import SQL file
print("\n[STEP 1/2] Importing Grazuri SQL file...")
print("-" * 100)

sql_file = r"c:\Users\Teamjoint company\Desktop\branchsystem\xygbfpsg_loans_populated.sql"

if not os.path.exists(sql_file):
    print(f"❌ SQL file not found: {sql_file}")
    sys.exit(1)

print(f"✓ Found SQL file: {sql_file}")
print("  Importing to database... (this may take a few minutes)")

try:
    # Import using mysql command
    cmd = f'mysql -u root -ppassword xygbfpsg_graz < "{sql_file}"'
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    
    if result.returncode == 0:
        print("✓ SQL file imported successfully!")
    else:
        # Check if it's just table exists errors
        if 'already exists' in result.stderr or 'Duplicate' in result.stderr:
            print("✓ SQL file imported (some tables already existed)")
        else:
            print(f"⚠ Import completed with warnings: {result.stderr[:200]}")
except Exception as e:
    print(f"⚠ Error importing SQL file: {str(e)}")
    print("  Continuing with data migration...")

# Step 2: Run complete data import
print("\n[STEP 2/2] Migrating all data to Haven Grazuri...")
print("-" * 100)

try:
    # Run the complete import script
    result = subprocess.run(
        ['python', 'import_complete_grazuri_data.py'],
        capture_output=True,
        text=True,
        timeout=600  # 10 minutes timeout
    )
    
    print(result.stdout)
    
    if result.returncode != 0:
        print(result.stderr)
        sys.exit(1)
        
except subprocess.TimeoutExpired:
    print("⚠ Import is taking longer than expected but may still be running...")
except Exception as e:
    print(f"❌ Error running import: {str(e)}")
    sys.exit(1)

print("\n" + "=" * 100)
print("✅ COMPLETE IMPORT PROCESS FINISHED!")
print("=" * 100)
