"""Ensure sports_center_db exists before migration."""
from __future__ import annotations

import os
import sys
from urllib.parse import urlparse


def main() -> None:
    sync_url = os.environ.get("SPORTS_CENTER_DATABASE_URL_SYNC", "")
    if not sync_url:
        print("SPORTS_CENTER_DATABASE_URL_SYNC not set", file=sys.stderr)
        return

    parsed = urlparse(sync_url.replace("+psycopg", ""))
    db_name = (parsed.path or "").lstrip("/") or "sports_center_db"

    import psycopg

    conn = psycopg.connect(
        host=parsed.hostname or "localhost",
        port=parsed.port or 5432,
        user=parsed.username,
        password=parsed.password,
        dbname="postgres",
        autocommit=True,
    )
    try:
        with conn.cursor() as cur:
            cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (db_name,))
            if cur.fetchone() is None:
                cur.execute(f'CREATE DATABASE "{db_name}"')
                print(f"Created database: {db_name}")
            else:
                print(f"Database exists: {db_name}")
    finally:
        conn.close()


if __name__ == "__main__":
    main()
