"""Apply db/migrations/20260405_norms_fta_comments.sql (COMMENT ON only, idempotent).

Usage (from repo root):
  python normbase/scripts/apply_migration_20260405_norms_fta_comments.py

Uses NORMBASE_DATABASE_URL or DATABASE_URL (.env loaded if present).

Safe on existing DBs: updates catalog comments only; does not change tables or data.
"""
from __future__ import annotations

import asyncio
import os
import re
import sys
from pathlib import Path

try:
    import asyncpg
except ImportError as e:
    raise SystemExit("asyncpg is required. Install project dependencies first.") from e


def _dsn() -> str:
    try:
        from dotenv import load_dotenv

        load_dotenv()
    except ImportError:
        pass
    raw = (os.getenv("NORMBASE_DATABASE_URL") or os.getenv("DATABASE_URL") or "").strip()
    if not raw:
        raise SystemExit("Set NORMBASE_DATABASE_URL or DATABASE_URL.")
    return re.sub(r"^postgresql\+asyncpg", "postgresql", raw, flags=re.I)


# Keep in sync with normbase/db/migrations/20260405_norms_fta_comments.sql
_STATEMENTS = [
    "COMMENT ON TABLE norms IS 'Core norm repository. Primary classification lens FTA = (formality_level, norm_type, governed_aspect).'",
    "COMMENT ON COLUMN norms.formality_level IS 'FTA · F — Formality: informal | formal | technical.'",
    "COMMENT ON COLUMN norms.norm_type IS 'FTA · T — Type (deontic): obligation | permission | prohibition.'",
    "COMMENT ON COLUMN norms.governed_aspect IS 'FTA · A — Aspect of governed behaviour: perceptual | cognitive | evaluative | behavioral | denotative.'",
    "COMMENT ON COLUMN norms.authority_level IS 'Supplementary to FTA: legal | industrial | organizational | group.'",
]


async def _run() -> None:
    conn = await asyncpg.connect(_dsn())
    try:
        for i, sql in enumerate(_STATEMENTS, 1):
            await conn.execute(sql)
            print(f"  [{i}/{len(_STATEMENTS)}] ok")
        print("Migration 20260405_norms_fta_comments applied successfully.")
    finally:
        await conn.close()


def main() -> None:
    repo_root = Path(__file__).resolve().parents[2]
    os.chdir(repo_root)
    asyncio.run(_run())


if __name__ == "__main__":
    try:
        main()
    except Exception as exc:
        print(f"Migration failed: {exc}", file=sys.stderr)
        sys.exit(1)
