"""CLI: import norms JSON into a field using a Field API key (aif_fk_…)."""

from __future__ import annotations

import argparse
import json
import os
import sys
from typing import Any
from urllib.parse import urljoin

import httpx


def _load_payload(path: str) -> dict[str, Any]:
    with open(path, encoding="utf-8") as f:
        raw = json.load(f)
    if isinstance(raw, list):
        return {"norms": raw}
    if isinstance(raw, dict) and "norms" in raw:
        return raw
    raise SystemExit("JSON must be an array of norms or an object with a 'norms' array.")


def main() -> None:
    p = argparse.ArgumentParser(description="Import norms via platform Field API key.")
    p.add_argument(
        "--base-url",
        default=os.getenv("AIF_PLATFORM_URL", "http://127.0.0.1:8020").rstrip("/"),
        help="Platform API base (default: AIF_PLATFORM_URL or http://127.0.0.1:8020)",
    )
    p.add_argument(
        "--key",
        default=os.getenv("AIF_FIELD_API_KEY", "").strip(),
        help="Field API key (default: AIF_FIELD_API_KEY)",
    )
    p.add_argument(
        "file",
        help="Path to JSON file: {\"norms\": [...]} or a JSON array",
    )
    args = p.parse_args()
    if not args.key:
        sys.exit("Missing --key or AIF_FIELD_API_KEY.")
    payload = _load_payload(args.file)
    url = urljoin(args.base_url + "/", "api/v1/norms/field-import")
    headers = {
        "Content-Type": "application/json",
        "X-Field-API-Key": args.key,
    }
    with httpx.Client(timeout=120.0) as client:
        r = client.post(url, headers=headers, json=payload)
    try:
        body = r.json()
    except Exception:
        body = r.text
    if r.status_code >= 400:
        print(json.dumps({"status": r.status_code, "detail": body}, ensure_ascii=False, indent=2))
        sys.exit(1)
    print(json.dumps(body, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
