#!/usr/bin/env python
"""Migration script for unit permission optimization"""
import sys
import os

# Add project root to path
project_root = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, project_root)

# Load .env file BEFORE importing any modules
from lawrisk.utils.env_loader import load_env
load_env('.env', override=False)

# Import migration functions
from lawrisk.utils.migrate_unit_permission import execute_migration, check_migration_status

if __name__ == "__main__":
    print("=" * 60)
    print("Unit Permission Optimization - Database Migration")
    print("=" * 60)
    print()

    # Check current status
    status = check_migration_status()
    print(f"Migration Status: {'Completed' if status['migration_complete'] else 'Not Completed'}")
    print()

    if not status['migration_complete']:
        response = input("Execute database migration? (y/N): ").strip().lower()
        if response == 'y':
            print("\nExecuting migration...")
            results = execute_migration()

            if results['success']:
                print("\nMigration SUCCESSFUL!")
                print("  - Schema migration: OK")
                print("  - Data migration: OK")
                print("\nYou can now restart the application:")
                print("  pkill -f 'python app.py'")
                print("  python app.py")
            else:
                print("\nMigration FAILED!")
                for error in results['errors']:
                    print(f"  Error: {error}")
        else:
            print("\nMigration skipped")
    else:
        print("Database migration already completed. No action needed.")

    print("\n" + "=" * 60)
