"""Usage ledger writer: which game (or app) used which library asset. One JSON line per asset per build.

record() never raises and never blocks a build (a bonus, like the library itself). The ledger path is NOT under
/srv/forge-assets (the Factory mounts that read-only): default /var/lib/forge-corp/library-usage/events.jsonl, which the
Factory container can write once the host dir exists and is owned by uid 1000 (see REPORT-F.md). Override: FORGE_LIBRARY_USAGE.
Pulled by tools/usage_pull.sh, folded by tools/usage_index.py. Event shape: see tools/usage_index.py.
"""
from __future__ import annotations

import json
import os
import time
from pathlib import Path

LEDGER = Path(os.environ.get("FORGE_LIBRARY_USAGE", "/var/lib/forge-corp/library-usage/events.jsonl"))


def record(picks: list[dict], user: str, platform: str = "omg", source: str = "build_pack", ledger: Path | None = None) -> int:
    """Append one event per pick (index rows: id, version, release). Returns events written, 0 on any failure."""
    try:
        if not user or not picks:
            return 0
        ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        lines = "".join(json.dumps({"ts": ts, "asset_id": a["id"], "version": a.get("version"), "release": a.get("release"),
                                    "user": user, "platform": platform, "source": source}, sort_keys=True) + "\n" for a in picks)
        path = ledger or LEDGER
        path.parent.mkdir(parents=True, exist_ok=True)
        with open(path, "a", encoding="utf-8") as f:  # one write call: O_APPEND keeps concurrent builds' lines whole
            f.write(lines)
        return len(picks)
    except Exception:
        return 0
