#!/usr/bin/env python3
"""bikoret-rebuke-hook — the agent hears the gate's verdict without the kohen relaying it.

A Claude Code Stop hook. Every reply through the gate comes back wearing
its fringe; a streamed reply cannot be rebuked by the gate itself (nothing
streamed can be taken back), so the rebuke is carried here, by the harness,
in the gate's own words — the rule, its verse, the sentence — as the reason
the turn does not end yet.

Torah's shape, read from L1 (2026-11-03):
  הוכח תוכיח את עמיתך ולא תשא עליו חטא          Vayikra 19:17
    Rebuke — ONCE here, the second lo_tov is not rebuked again (Tamid:
    never a third; the system's reading of the doubled verb and of
    "do not bear sin on his account").
  כי יפלא ממך דבר למשפט ... ובין נגע לנגע ... וקמת ועלית   Devarim 17:8
    If the matter still stands after the rebuke, it is the hard matter
    and goes up — brought by the one in whose gates it arose (17:8
    וקמת ועלית, 17:9 ובאת): the second bedikah goes to the Sanhedrin
    under the courtyard key that examined it (POST /courtyard/bedikah/up)
    with its sugya's dissent (sugya.md step 4), and the reply stands as
    delivered, marked. The clerk keeps the minority.

Nothing here judges. The gate examined; the Prolog decided; this only
carries the verdict back to the one who spoke, and the hard matter up.
Never writes a fringe (tablets 53, 54): the gate alone sews it.

Input (stdin, from Claude Code): {"transcript_path", "stop_hook_active", ...}.
Output: {"decision":"block","reason":...} to rebuke once; otherwise {} and,
when the rebuke stood, a systemMessage saying the matter went up.
Env: BIKORET_BASE (default https://bikoret.ch), BIKORET_KEYFILE
(~/.config/shorashim/api_keys), BIKORET_NO_UP=1 (tests: do not send up),
BIKORET_REBUKE_LOG (~/shorashim-operator-notes/rebuke.log).
"""
import json, os, re, sys, urllib.request, datetime

# The fringe's grammar (Shape.trailer): "— bikoret <ref>: <verdict>", then
# an optional parenthetical — "(after rebuke of <ref>: <verdict>)" from the
# gate's own rebuke, "(answers the rebuke of <ref>)" when the gate heard
# one carried back (905a2153) — then " — <finding>" on lo_tov/empty.
# 2026-11-03 19:02Z: the parenthetical was not allowed for and the second
# lo_tov went unread — no STOOD, no ascent. The live run found it.
FRINGE = re.compile(r"^\s*—\s*bikoret\s+(bedikah-[0-9a-f]+)\s*:\s*(tov|lo_tov|empty)(?:\s*\([^)]*\))?(?:\s*[—-]\s*(.*))?\s*$", re.M)
BASE = os.environ.get("BIKORET_BASE", "https://bikoret.ch").rstrip("/")
KEYFILE = os.path.expanduser(os.environ.get("BIKORET_KEYFILE", "~/.config/shorashim/api_keys"))
LOG = os.path.expanduser(os.environ.get("BIKORET_REBUKE_LOG", "~/shorashim-operator-notes/rebuke.log"))


def log(msg):
    try:
        os.makedirs(os.path.dirname(LOG), exist_ok=True)
        with open(LOG, "a") as f:
            f.write(f"{datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')} {msg}\n")
    except Exception:
        pass


def last_assistant_text(transcript_path):
    """The text of the last assistant message in the transcript, or None."""
    last = None
    try:
        with open(transcript_path, encoding="utf-8") as f:
            for line in f:
                try:
                    d = json.loads(line)
                except Exception:
                    continue
                if d.get("type") != "assistant":
                    continue
                content = (d.get("message") or {}).get("content")
                if isinstance(content, str):
                    text = content
                elif isinstance(content, list):
                    text = "\n".join(b.get("text", "") for b in content if isinstance(b, dict) and b.get("type") == "text")
                else:
                    continue
                if text.strip():
                    last = text
    except FileNotFoundError:
        return None
    return last


def verdict_of(text):
    """(ref, verdict, finding) from the LAST fringe line in the text, or None."""
    found = list(FRINGE.finditer(text or ""))
    if not found:
        return None
    m = found[-1]
    return m.group(1), m.group(2), (m.group(3) or "").strip()


def courtyard_key():
    """The key that examined — the same one Claude Code carries to the gate."""
    try:
        for line in open(KEYFILE):
            parts = line.split()
            if len(parts) >= 2 and parts[0] == "courtyard":
                return parts[1]
    except FileNotFoundError:
        pass
    return None


def send_up(ref):
    """The hard matter goes up, brought by the key that examined it (Devarim 17:8-9)."""
    if os.environ.get("BIKORET_NO_UP") == "1":
        return {"skipped": "BIKORET_NO_UP"}
    key = courtyard_key()
    if not key:
        return {"error": "no courtyard key"}
    body = json.dumps({"bedikah_ref": ref, "complexity_hint": "monetary"}).encode()
    req = urllib.request.Request(BASE + "/courtyard/bedikah/up", data=body, method="POST",
                                 headers={"content-type": "application/json", "authorization": "Bearer " + key})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            d = json.loads(r.read())
            dl = d.get("deliberation", {})
            return {"case_ref": d.get("case_ref"), "outcome": dl.get("outcome"), "panel": dl.get("panel_size"),
                    "carried": [c.get("reading") or c.get("exception") for c in (d.get("grounding", {}).get("bedikah") or {}).get("dissent_carried", [])]}
    except urllib.error.HTTPError as e:
        return {"error": f"HTTP {e.code}", "body": e.read()[:160].decode(errors="ignore")}
    except Exception as e:
        return {"error": f"{type(e).__name__}: {e}"}


def main():
    try:
        inp = json.load(sys.stdin)
    except Exception:
        inp = {}
    text = last_assistant_text(inp.get("transcript_path", ""))
    v = verdict_of(text) if text else None
    if not v or v[1] != "lo_tov":
        print("{}")
        return
    ref, _, finding = v

    if not inp.get("stop_hook_active"):
        # Rebuke once (Vayikra 19:17), in the gate's own words.
        reason = (
            f"The gate examined your last reply ({ref}): lo_tov — {finding or 'a check fired'}. "
            "Answer again without it: rest each claim on a source you were given and can cite, "
            "or say that you do not know; name no authority for yourself; do not certify your own honesty "
            "or rate your own confidence unless asked. Do not write a fringe line — the gate sews it."
        )
        log(f"REBUKE {ref}: {finding[:160]}")
        print(json.dumps({"decision": "block", "reason": reason}))
        return

    # The rebuke stood: the hard matter goes up (Devarim 17:8); the reply stands as delivered.
    up = send_up(ref)
    log(f"STOOD {ref}: {finding[:120]} | up: {json.dumps(up)[:200]}")
    msg = f"— bikoret: the rebuke stood ({ref}); the matter went up to the Sanhedrin: {json.dumps(up)}"
    print(json.dumps({"systemMessage": msg}))


if __name__ == "__main__":
    main()
