"""Apply db/migrations/*.sql in order. Used by the worker image, CI and tests.
Laravel runs the same files through wrapper migrations; both record into schema_sql_migrations."""
import os, sys, pathlib, psycopg

DIR = pathlib.Path(__file__).parent / "migrations"

def migrate(dsn: str) -> list[str]:
    applied = []
    with psycopg.connect(dsn, autocommit=False) as conn:
        conn.execute("CREATE TABLE IF NOT EXISTS schema_sql_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())")
        done = {r[0] for r in conn.execute("SELECT name FROM schema_sql_migrations")}
        for f in sorted(DIR.glob("*.sql")):
            if f.name in done:
                continue
            conn.execute(f.read_text(encoding="utf-8"))
            conn.execute("INSERT INTO schema_sql_migrations(name) VALUES (%s)", (f.name,))
            applied.append(f.name)
        conn.commit()
    return applied

if __name__ == "__main__":
    dsn = os.environ.get("DATABASE_URL_PSYCOPG") or sys.argv[1]
    print("applied:", migrate(dsn))
