#!/usr/bin/env python3
"""Read the Wikipedia pages an analyst supplied for one run's events.

Two modes, both driven by the enrichment screen:

    python3 worker/enrich_run.py suggest <RUN_ID>
        For every event detected in the run, search Wikipedia and write a
        pre-filled page guess. Writes <RUN>_enrich_suggest.json.

    python3 worker/enrich_run.py read <RUN_ID>
        Read <RUN>_enrich_req.json ({event: url}), fetch each page, have Claude
        pull the fixtures out, and write <RUN>_enrich.json for preview.
        Nothing is written to the database here -- the analyst confirms first.

Progress goes to <RUN>_enrich_status.json so the page can poll it.
"""
from __future__ import annotations

import json
import sys
import traceback
from pathlib import Path

BASE = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(BASE))
# Apache runs this as www-data, which has no ~/.local site-packages. Third-party
# deps live in vendor/ so the web path and the shell path resolve identically.
_vendor = BASE / "vendor"
if _vendor.is_dir():
    sys.path.insert(0, str(_vendor))

from engine.wiki_enrich import _client, enrich_from_url, suggest_url  # noqa: E402

CFG = json.loads((BASE / "worker" / "config.json").read_text())
EXPORTS = Path(CFG["exports_dir"])


def _status(run_id: str, **kw) -> None:
    (EXPORTS / f"{run_id}_enrich_status.json").write_text(json.dumps(kw))


def _events(run_id: str) -> list[dict]:
    p = EXPORTS / f"{run_id}_events.json"
    return json.loads(p.read_text()) if p.exists() else []


def cmd_suggest(run_id: str) -> int:
    evs = _events(run_id)
    _status(run_id, phase="suggest", state="running", done=0, total=len(evs))
    out = []
    for i, e in enumerate(evs, 1):
        try:
            url = suggest_url(e["event_name"], e.get("season"))
        except Exception:                                   # noqa: BLE001
            url = ""
        out.append({**e, "url": url})
        _status(run_id, phase="suggest", state="running", done=i, total=len(evs),
                detail=e["event_name"])
    (EXPORTS / f"{run_id}_enrich_suggest.json").write_text(json.dumps(out, indent=1))
    _status(run_id, phase="suggest", state="done", done=len(evs), total=len(evs))
    return 0


def cmd_read(run_id: str) -> int:
    req_path = EXPORTS / f"{run_id}_enrich_req.json"
    if not req_path.exists():
        _status(run_id, phase="read", state="error", detail="no request file")
        return 1
    req = json.loads(req_path.read_text())          # [{event_name, season, url}]
    _status(run_id, phase="read", state="running", done=0, total=len(req))
    client = _client()
    results = []
    for i, r in enumerate(req, 1):
        ev, url, season = r.get("event_name", ""), (r.get("url") or "").strip(), r.get("season")
        _status(run_id, phase="read", state="running", done=i - 1, total=len(req), detail=ev)
        try:
            res = enrich_from_url(client, ev, season, url)
        except Exception as exc:                            # noqa: BLE001
            res = {"status": "error", "url": url, "fixtures": [], "label": "",
                   "note": f"{type(exc).__name__}: {exc}"[:300]}
        res["event_name"] = ev
        res["season"] = season
        results.append(res)
        _status(run_id, phase="read", state="running", done=i, total=len(req), detail=ev)
    (EXPORTS / f"{run_id}_enrich.json").write_text(json.dumps(results, indent=1))
    n = sum(len(r["fixtures"]) for r in results)
    _status(run_id, phase="read", state="done", done=len(req), total=len(req),
            detail=f"{n} fixtures read")
    return 0


def main() -> int:
    if len(sys.argv) < 3:
        print(__doc__)
        return 2
    cmd, run_id = sys.argv[1], sys.argv[2]
    try:
        if cmd == "suggest":
            return cmd_suggest(run_id)
        if cmd == "read":
            return cmd_read(run_id)
    except Exception as exc:                                # noqa: BLE001
        traceback.print_exc()
        _status(run_id, phase=cmd, state="error", detail=f"{type(exc).__name__}: {exc}"[:300])
        return 1
    print(f"unknown command {cmd!r}")
    return 2


if __name__ == "__main__":
    raise SystemExit(main())
