#!/usr/bin/env python
"""Run Alembic migrations before starting the app.

This script is designed as a Docker entrypoint pre-migration step.
It runs `alembic upgrade head` and then starts uvicorn.
"""

import subprocess
import sys
import os


def run_migrations():
    db_url = os.environ.get("DATABASE_URL_SYNC") or os.environ.get("DATABASE_URL", "").replace("+asyncpg", "+psycopg2", 1)
    if not db_url:
        print("WARNING: No DATABASE_URL found, skipping migrations")
        return

    env = os.environ.copy()
    env["DATABASE_URL_SYNC"] = db_url

    result = subprocess.run(
        ["alembic", "-c", "alembic.ini", "upgrade", "head"],
        env=env,
        cwd="/app",
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        print(f"Migration failed:\n{result.stdout}\n{result.stderr}")
        sys.exit(1)
    print(f"Migration successful:\n{result.stdout}")


if __name__ == "__main__":
    run_migrations()
    os.execvp(
        "uvicorn",
        ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000",
         "--workers", "4", "--loop", "uvloop", "--http", "httptools"],
    )
