#!/usr/bin/env python3
"""
Railway release command — runs migrations + optional seed data.

Set SEED_ON_DEPLOY=true in Railway env vars to auto-seed test users
on PR environments. Seeding is idempotent (skips existing records).

Usage (called by railway.toml releaseCommand):
  python -m scripts.release
"""

import asyncio
import subprocess
import sys

from app.core.config import settings


def run_migrations() -> None:
    """Run alembic upgrade head."""
    print("\n[release] Running database migrations...")
    result = subprocess.run(
        ["alembic", "upgrade", "head"],
        capture_output=False,
    )
    if result.returncode != 0:
        print("[release] ERROR: Migrations failed!")
        sys.exit(1)
    print("[release] Migrations complete.")


async def seed_test_data() -> None:
    """Seed test users (direct DB, no HTTP needed)."""
    print("\n[release] Seeding test users...")
    from scripts.seed_test_users import main as seed_users
    await seed_users()
    print("[release] Test users seeded.")


def main() -> None:
    run_migrations()

    if settings.SEED_ON_DEPLOY:
        print("[release] SEED_ON_DEPLOY=true — seeding test data...")
        asyncio.run(seed_test_data())
    else:
        print("[release] SEED_ON_DEPLOY not set — skipping seed data.")

    print("\n[release] Release complete!")


if __name__ == "__main__":
    main()
