#!/usr/bin/env python3
"""snag-axi — agent-native CLI for the Snagboard friction pinboard.

Built to the AXI principles (https://axi.md/): TOON-style output
(minimal default schema — 3-4 fields per list item, more via --fields),
pre-computed aggregates, truncation with --full escape hatch,
structured errors (0 success / 1 error / 2 usage), content-first home
view, and contextual next-step hints after every output.

Humans pin. We work.
"""
import argparse
import json
import os
import re
import sys
import urllib.error
import urllib.request

BOARD = os.environ.get("SNAGBOARD_URL", "http://127.0.0.1:8090")
TRUNC = 480  # chars per long field unless --full

STATUSES = ("pinned", "claimed", "in_progress", "done", "wontfix")
VALID_RESULT_KINDS = ("demo", "script", "fix", "pr", "doc", "note")

# TOON list schemas: default is decision-grade (3-4 fields), --fields adds more.
LIST_FIELDS = ("id", "status", "title", "author")
EXTRA_FIELDS = ("tags", "problem", "direction", "media", "results")


def _first_line(s):
    return (s or "").replace("\n", " ").strip()


def api(method, path, data=None):
    payload = json.dumps(data).encode() if data is not None else None
    req = urllib.request.Request(BOARD + path, data=payload, method=method,
                                 headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        detail = e.read().decode(errors="replace")[:300]
        print(f"ERROR {e.code} on {path}: {detail}")
        sys.exit(1)
    except Exception as e:
        print(f"ERROR: cannot reach board at {BOARD} ({e})")
        sys.exit(1)


def clip(s, full=False):
    if not s:
        return ""
    if full or len(s) <= TRUNC:
        return s
    return s[:TRUNC] + f" …[+{len(s) - TRUNC}c — rerun with --full]"


def toon_row(p, fields, full=False):
    """One TOON row: comma-joined fields, values quoted when they need it."""
    vals = []
    for f in fields:
        if f == "id":
            v = p["id"]
        elif f == "status":
            v = p["status"]
        elif f == "title":
            v = _first_line(clip(p["title"], full))
        elif f == "author":
            v = _first_line(p["author"])
        elif f == "tags":
            v = ",".join(p.get("tags") or [])
        elif f == "problem":
            c = p.get("card") or {}
            v = clip(c.get("problem") or "", full=False)
        elif f == "direction":
            c = p.get("card") or {}
            v = f"{c.get('friction_type', '')} {c.get('suggested_direction', '')}".strip()
        elif f == "media":
            v = ",".join(m["path"].rsplit("/", 1)[-1] for m
                         in (p.get("media") or []))
        elif f == "results":
            v = ",".join(r["ref"] for r in (p.get("results") or []))
        else:
            v = ""
        v = str(v or "")
        if v == "":
            vals.append("")
        elif re.search(r'[,"]', v) or " " in v:
            vals.append('"%s"' % v.replace('"', '""'))
        else:
            vals.append(v)
    return "  " + ",".join(vals)


def board_home(pins):
    """Principle 8 home view: bin:, description:, live state."""
    bp = os.path.normpath(sys.argv[0])
    home = os.path.expanduser("~")
    if bp.startswith(home):
        bp = "~" + bp[len(home):]
    counts = {}
    for p in pins:
        counts[p["status"]] = counts.get(p["status"], 0) + 1
    agg = " ".join(f"{k}={v}" for k, v in sorted(counts.items()))
    fresh = [p for p in pins if p["status"] == "pinned"]
    print(f"bin: {bp}")
    print(f"description: Snagboard friction pinboard at {BOARD} — humans pin frictions, agents claim and close them")
    print(f"count: {len(pins)} pins [{agg}] — {len(fresh)} open")
    return fresh


def fmt_pin(p, full=False):
    lines = []
    tag = {"pinned": "●  NEW  ", "claimed": "◐", "in_progress": "◑",
           "done": "✓", "wontfix": "✗"}[p["status"]]
    lines.append(f"{tag} {p['id']}  {p['title']}")
    meta = [p["author"], p["status"]]
    if p.get("status_note"):
        meta.append(f"({p['status_note']})")
    if p.get("claimed_by"):
        meta.append(f"claimed:{p['claimed_by']}")
    if p.get("tags"):
        meta.append("tags:" + ",".join(p["tags"]))
    lines.append("   " + " | ".join(meta))
    if p["body"]:
        lines.append(f"   note: {clip(p['body'], full)}")
    card = p.get("card")
    if card:
        lines.append(f"   card: {card.get('problem', '?')}")
        if card.get("friction_type"):
            lines.append(f"         type:{card['friction_type']}"
                         f" {card.get('suggested_direction', '')}")
        ev = card.get("evidence") or []
        if ev:
            lines.append(f"         evidence: {'; '.join(e[:1] for e in ev) if isinstance(ev[0], list) else '; '.join(clip(x, full)[:90] for x in ev[:4])}")
    for m in p.get("media", []):
        line = f"   media[{m['id']}]: {m['kind']} {m['name']}"
        if m.get("transcript"):
            line += f"\n      transcript: {clip(m['transcript'], full)}"
        else:
            line += f" [transcript: {'unavailable' if m.get('transcript') is None else 'pending'}]"
        if m.get("analysis"):
            line += f"\n      analysis: {clip(m['analysis'], full)}"
        lines.append(line + f"  (fetch: {BOARD}{m['path']})")
    for r in p.get("results", []):
        lines.append(f"   result[{r['kind']}]: {r['ref']} — {r['summary']}")
    for a in p.get("asks") or []:
        tag = "open" if a.get("open") else "answered"
        line = f"   ask[{tag}]: {a.get('by', '??')} asks: {clip(a.get('q') or '', full)}"
        if a.get("ctx"):
            line += f"\n         why: {clip(a['ctx'], full)}"
        if a.get("a"):
            line += f"\n         {a.get('by_a') or 'owner'} answered: {clip(a['a'], full)}"
        lines.append(line)
    return "\n".join(lines)


def _actionable(p):
    """need_work = actionable pins only. Ingest classifies junk as
    friction_type "unknown" (or leaves card None) — those need a human
    follow-up, not an agent: the loop must never point at them
    ("do not fabricate frictions"). The server mirrors this for
    /api/board.toon — keep the two in lockstep."""
    if p.get("status") != "pinned":
        return False
    c = p.get("card")
    return isinstance(c, dict) and c.get("friction_type") not in (None, "unknown")


def next_steps(p):
    s = p["status"]
    b = f"--board {BOARD} " if BOARD != "http://127.0.0.1:8090" else ""
    open_ask = next((a for a in (p.get("asks") or []) if a.get("open")), None)
    if open_ask:
        return (f"pin awaits the author's answer — do NOT re-work it; re-read: "
                f"snag-axi {b}answers {p['id']}   (asks[].open=false ⇒ the answer is in asks[].a)")
    if s == "pinned":
        return f"next: snag-axi {b}claim {p['id']} --as <agent>   (or {b}show {p['id']} --full first)"
    if s in ("claimed", "in_progress"):
        return (f"next: build the fix, then snag-axi {b}result {p['id']} --kind "
                f"{json.dumps(VALID_RESULT_KINDS)[1:-1]} "
                f"--ref <url/path> --summary '...'   and finally snag-axi {b}done {p['id']} --summary '...'")
    if s == "done":
        return f"pin closed. next: snag-axi {b}(find another pin)"
    return f"next: snag-axi {b}"


def cmd_digest(args):
    fields_raw = getattr(args, "fields", "") or ""
    fields = tuple(f.strip() for f in fields_raw.split(",") if f.strip()) \
        or LIST_FIELDS
    bad = [f for f in fields if f not in LIST_FIELDS + EXTRA_FIELDS]
    if bad:
        print(f"ERROR 2: unknown field(s) {', '.join(bad)} — choose from "
              f"{' '.join(LIST_FIELDS + EXTRA_FIELDS)}")
        sys.exit(2)
    b = api("GET", "/api/board")
    pins = b["pins"]
    fresh = board_home(pins)
    if not pins:  # principle 5: definitive empty state, never silent
        print(f"pins[0]{{{','.join(fields)}}}:")
        print("next: board is empty — nothing pinned yet.")
        print("help[1]:")
        print(f"  Run curl -F 'title=...' -F 'body=...' -F 'author=...' {BOARD}/api/pins  (pin the first friction)")
        return
    print(f"pins[{len(pins)}]{{{','.join(fields)}}}:")
    full = getattr(args, "full", False)
    for p in pins:
        print(toon_row(p, fields, full=full))
    actionable = [pp for pp in fresh if _actionable(pp)]
    bflag = f"--board {BOARD} " if BOARD != "http://127.0.0.1:8090" else ""
    if actionable:
        # server sorts pins newest-first → oldest actionable unclaimed is the last one
        oldest = actionable[-1]
        need_ids = [pp['id'] for pp in reversed(actionable)]
        print(f"need_work[{len(actionable)}]: " + ",".join(need_ids))
    else:
        unact_note = (f" ({len(fresh)} open pin(s) are friction_type=unknown — "
                      "human follow-up, not agent work)" if fresh else "")
        print(f"need_work[0]: — no actionable pins{unact_note}")
    # awaiting: claimed pins blocked on a HUMAN answer to an agent question —
    # do NOT re-work them; re-read the pin once the answer lands. Between
    # need_work and next: (server /api/board.toon mirrors this — lockstep).
    awaiting = [pp for pp in pins for a in (pp.get("asks") or []) if a.get("open")]
    if awaiting:
        print(f"awaiting[{len(awaiting)}]:")
        for pp in awaiting:
            a = next(x for x in pp["asks"] if x.get("open"))
            line = f"  {pp['id']},{a.get('by') or '??'} asked: \"{(a.get('q') or '').strip()}\""
            if len(line) > 120:
                marker = f"…[+{len(a.get('q') or '')}q]"
                line = line[:120 - len(marker)] + marker
            print(line)
    else:
        print("awaiting[0]:")
    if actionable:
        print(f"next: {oldest['id']} is oldest actionable unclaimed → claim: "
              f"snag-axi {bflag}claim {oldest['id']} --as <agent>")
    else:
        print("next: no actionable pins; exit quietly")
    print("help[4]:")
    print(f"  Run snag-axi {bflag}show <pin> --full   (evidence, transcripts, results, asks)")
    print(f"  Run snag-axi {bflag}ask <pin> --as <agent> '<question>'   (ask the pin's author; only while you claim the pin)")
    print(f"  Run snag-axi {bflag}answers <pin>   (the author's answers to your open questions)")
    print(f"  Run curl -o out.<ext> {BOARD}<media-path>   (fetch media)")


def cmd_show(args):
    p = api("GET", f"/api/pins/{args.pin}")
    print(fmt_pin(p, full=args.full))
    print()
    print(next_steps(p))


def cmd_claim(args):
    p = api("POST", f"/api/pins/{args.pin}/claim", {"agent": args.as_agent})
    print(f"claimed {p['id']} as {p.get('claimed_by')}: status={p['status']!r}")
    card = p.get("card")
    if card:
        print(f"problem: {card.get('problem', '?')}")
        print(f"direction: {card.get('suggested_direction', '?')}")
    else:
        print("no structured card yet — read note/transcripts (show --full).")
    print(next_steps(p))


def cmd_status(args):
    if args.status not in STATUSES:
        print(f"ERROR: status must be one of {', '.join(STATUSES)}")
        sys.exit(2)
    body = {"status": args.status, "note": args.note or ""}
    if args.as_agent:
        body["agent"] = args.as_agent
    p = api("POST", f"/api/pins/{args.pin}/status", body)
    print(f"{p['id']} -> status={p['status']!r}" + (f" note={p.get('status_note')!r}" if p.get("status_note") else ""))
    if args.status == "pinned" and p.get("results"):
        print("note: reverting status; results remain attached.")
    print(next_steps(p))


def cmd_result(args):
    if args.kind not in VALID_RESULT_KINDS:
        print(f"ERROR: kind must be one of {', '.join(VALID_RESULT_KINDS)}")
        sys.exit(2)
    p = api("POST", f"/api/pins/{args.pin}/result",
            {"kind": args.kind, "ref": args.ref, "summary": args.summary})
    print(f"result[{args.kind}] attached to {p['id']}: {args.ref}")
    print(next_steps(p))


def cmd_ask(args):
    body = {"agent": args.as_agent, "question": args.question}
    if args.why:
        body["context"] = args.why
    try:
        p = api("POST", f"/api/pins/{args.pin}/ask", body)
    except SystemExit:
        raise
    aid = (p.get("asks") or [{}])[-1]["id"] if p.get("asks") else "?"
    print(f"question {aid} posted to the author of {p['id']} — now WAIT: do not re-claim or pile more questions on top of it.")
    print(f"next: snag-axi {('--board ' + BOARD + ' ') if BOARD != 'http://127.0.0.1:8090' else ''}answers {p['id']}   (re-read once the answer lands; asks[].open=false ⇒ reads asks[].a)")


def cmd_answers(args):
    p = api("GET", f"/api/pins/{args.pin}")
    asks = p.get("asks") or []
    if not asks:
        print(f"{p['id']}: no questions on this pin")
        print(next_steps(p))
        return
    for a in asks:
        if a.get("open"):
            print(f"open  [{a['id']}]: {a.get('by', '??')} asks: {a.get('q') or ''}")
            if a.get("ctx"):
                print(f"        why: {a['ctx']}")
        else:
            print(f"answer[{a['id']}]: {(a.get('by_a') or 'owner')} answered: {a.get('a') or ''}")
            print(f"        (question was: {a.get('q') or ''})")
    print(next_steps(p))


def cmd_done(args, agent=None):
    p = api("POST", f"/api/pins/{args.pin}/status",
            {"status": "done", "note": args.summary or "", "agent": agent})
    print(f"{p['id']} marked done. {args.summary or ''}".strip())
    n = len(p.get("results", []))
    if not n:
        print("warning: no results attached — attach evidence first "
              "(snag-axi result ...); a done pin with zero artifacts is a claim, not a fix.")
    bflag = f"--board {BOARD} " if BOARD != "http://127.0.0.1:8090" else ""
    print(f"next: snag-axi {bflag}   (board digest — find the next pin)")


def main(argv=None):
    global BOARD
    argv = list(sys.argv[1:] if argv is None else argv)
    # --board <url> / --board=<url> may sit anywhere on the command line;
    # self-contained addressing without relying on env for remote agents.
    i = 0
    while i < len(argv):
        if argv[i] == "--board" and i + 1 < len(argv):
            BOARD = argv[i + 1]
            del argv[i:i + 2]
        elif argv[i].startswith("--board="):
            BOARD = argv[i].split("=", 1)[1]
            del argv[i]
        else:
            i += 1
    ap = argparse.ArgumentParser(
        prog="snag-axi", description="agent-native CLI for the Snagboard pinboard "
                                      "(--board <url> sets the board, default $SNAGBOARD_URL)",
        add_help=False)
    sub = ap.add_subparsers(dest="cmd")

    spb = sub.add_parser("board", help="live board digest (no args does the same)")
    spb.add_argument("--fields", default="",
                     help="extra list columns — comma list from: "
                          + " ".join(EXTRA_FIELDS))
    spb.add_argument("--full", action="store_true",
                     help="no truncation of list fields")
    sps = sub.add_parser("show", help="one pin in full")
    sps.add_argument("pin")
    sps.add_argument("--full", action="store_true", help="no truncation")

    spc = sub.add_parser("claim", help="claim a pin (idempotent per agent)")
    spc.add_argument("pin")
    spc.add_argument("--as", dest="as_agent", default=os.environ.get("AGENT_ID", "agent"),
                     help="who is claiming (default: $AGENT_ID or 'agent')")

    sps = sub.add_parser("status", help="set status: " + " ".join(STATUSES))
    sps.add_argument("pin")
    sps.add_argument("--status", required=True)
    sps.add_argument("--note", default="")
    sps.add_argument("--as", dest="as_agent", default=None,
                     help="who is acting (required to close pins you claimed)")

    spr = sub.add_parser("result", help="attach a work artifact")
    spr.add_argument("pin")
    spr.add_argument("--kind", required=True)
    spr.add_argument("--ref", required=True, help="url / path / ref for the artifact")
    spr.add_argument("--summary", required=True)

    spd = sub.add_parser("done", help="mark a pin done")
    spd.add_argument("pin")
    spd.add_argument("--summary", default="")
    spd.add_argument("--as", dest="as_agent", default=None,
                     help="who is closing (matched against claim owner)")

    spa = sub.add_parser("ask", help="ask the pin's author a question (only while you claim the pin; one open question at a time)")
    spa.add_argument("pin")
    spa.add_argument("question")
    spa.add_argument("--why", default="", help="optional: why it blocks your work")
    spa.add_argument("--as", dest="as_agent", default=os.environ.get("AGENT_ID", "agent"),
                     help="who is asking (must match the claim owner)")

    spa2 = sub.add_parser("answers", help="your open question(s) + the author's answers")
    spa2.add_argument("pin")

    spj = sub.add_parser("dump", help="escape hatch: raw JSON of whole board")
    spj.add_argument("pin", nargs="?")

    # add_help=False above keeps no-args a LIVE board digest (Principle 8) —
    # but top-level -h/--help must still print a reference (Principle 10).
    # Catch it before argparse: help wins over home view when explicitly asked.
    if argv and argv[0] in ("-h", "--help"):
        ap.print_help()
        sys.exit(0)

    a = ap.parse_args(argv)
    if a.cmd in (None, "board"):
        cmd_digest(a)
    elif a.cmd == "show":
        cmd_show(a)
    elif a.cmd == "claim":
        cmd_claim(a)
    elif a.cmd == "status":
        cmd_status(a)
    elif a.cmd == "result":
        cmd_result(a)
    elif a.cmd == "done":
        cmd_done(a, agent=a.as_agent)
    elif a.cmd == "ask":
        cmd_ask(a)
    elif a.cmd == "answers":
        cmd_answers(a)
    elif a.cmd == "dump":
        print(json.dumps(api("GET", f"/api/pins/{a.pin}") if a.pin else api("GET", "/api/board"),
                         indent=1))
    else:
        ap.print_help()
        sys.exit(2)


if __name__ == "__main__":
    main()
