#!/usr/bin/env python3
"""
Database Migration Helper Script
Wrapper for Alembic commands
"""
import subprocess
import sys
import os
from pathlib import Path

# Change to central-backend directory
os.chdir(Path(__file__).parent.parent)


def run_command(cmd):
    """Run a command and print output"""
    print(f"Running: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=False)
    return result.returncode


def main():
    if len(sys.argv) < 2:
        print("""
AI360 Database Migration Helper

Usage:
    python db_migrate.py <command> [args]

Commands:
    upgrade     - Upgrade to latest migration (or specify revision)
    downgrade   - Downgrade by one revision (or specify revision)
    current     - Show current revision
    history     - Show migration history
    heads       - Show current heads
    generate    - Auto-generate a new migration (requires message)
    new         - Create a new empty migration (requires message)

Examples:
    python db_migrate.py upgrade            # Upgrade to latest
    python db_migrate.py upgrade head       # Same as above
    python db_migrate.py upgrade +1         # Upgrade by one
    python db_migrate.py downgrade -1       # Downgrade by one
    python db_migrate.py downgrade base     # Downgrade all
    python db_migrate.py current            # Show current
    python db_migrate.py history            # Show history
    python db_migrate.py generate "Add new table"
    python db_migrate.py new "Manual migration"
        """)
        return 1

    command = sys.argv[1]

    if command == "upgrade":
        revision = sys.argv[2] if len(sys.argv) > 2 else "head"
        return run_command(["alembic", "upgrade", revision])

    elif command == "downgrade":
        revision = sys.argv[2] if len(sys.argv) > 2 else "-1"
        return run_command(["alembic", "downgrade", revision])

    elif command == "current":
        return run_command(["alembic", "current"])

    elif command == "history":
        return run_command(["alembic", "history", "--verbose"])

    elif command == "heads":
        return run_command(["alembic", "heads"])

    elif command == "generate":
        if len(sys.argv) < 3:
            print("Error: Please provide a migration message")
            print("Usage: python db_migrate.py generate 'Add new table'")
            return 1
        message = sys.argv[2]
        return run_command(["alembic", "revision", "--autogenerate", "-m", message])

    elif command == "new":
        if len(sys.argv) < 3:
            print("Error: Please provide a migration message")
            print("Usage: python db_migrate.py new 'Manual migration'")
            return 1
        message = sys.argv[2]
        return run_command(["alembic", "revision", "-m", message])

    else:
        print(f"Unknown command: {command}")
        return 1


if __name__ == "__main__":
    sys.exit(main())
