"""Route an issue using three PAW programs. Requires Python 3.10+."""
import argparse
import json
from pathlib import Path
import programasweights as paw

COMPILER = "paw-4b-qwen3-0.6b"
PROGRAM_FILE = Path(__file__).with_name("triage-programs.json")
SPECS = {
    "kind": (
        "Classify this GitHub issue. Output exactly bug, feature, or question. "
        "A bug describes existing behavior failing. A feature asks to add "
        "new behavior. A question asks how to do something. "
        "Example: Export crashes every time => bug. "
        "Example: Add a PDF export button => feature. "
        "Example: How do I export my notes? => question."
    ),
    "area": (
        "Choose the component of this GitHub issue. Output exactly editor, "
        "export, or other. Editor means typing and formatting notes. "
        "Export means saving a copy to a file. Everything else is other. "
        "Example: The PDF download is blank => export. "
        "Example: The cursor jumps when typing => editor. "
        "Example: I cannot log in => other."
    ),
    "detail": (
        "Does this GitHub issue describe a specific symptom, concrete request, "
        "or clear question? Answer exactly clear or unclear. "
        "Example: It doesn't work => unclear. "
        "Example: Pressing Export PDF saves an empty file => clear."
    ),
}

def compile_programs():
    ids = {}
    for name, specification in SPECS.items():
        program = paw.compile(specification, compiler=COMPILER, public=False)
        if not program.id:
            raise RuntimeError(f"Could not compile {name}: {program.error}")
        ids[name] = program.id
    temporary = PROGRAM_FILE.with_suffix(".tmp")
    temporary.write_text(json.dumps(ids, indent=2) + "\n")
    temporary.replace(PROGRAM_FILE)
    return ids


def route(issue, ids):
    outputs = {name: paw.function(ids[name], remote=True)(issue) for name in SPECS}
    kind, area, detail = [outputs[name].strip().lower() for name in SPECS]
    if kind in {"bug", "feature"} and area in {"editor", "export"} and detail == "clear":
        return {"action": "label", "labels": [kind, area], "outputs": outputs}

    generalist = paw.function(None, interpreter="Qwen/Qwen3-0.6B")
    task = (
        "You are the maintainer of the Notes app. Ask the user which action they took "
        "or what they saw on screen. Write one specific follow-up question in the second person."
        f"\nIssue: {issue}"
    )
    question = generalist(task, max_tokens=100, temperature=0)
    return {"action": "generalist", "question": question, "outputs": outputs}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--compile", action="store_true", help="Create a private program for each job")
    parser.add_argument("issue", nargs="?")
    args = parser.parse_args()
    if not args.compile and not args.issue:
        parser.error("Pass --compile or an issue in quotes.")
    if args.compile:
        print(json.dumps(compile_programs(), indent=2))
    if args.issue:
        if not PROGRAM_FILE.is_file():
            parser.error("Run --compile once to create the three specialists.")
        programs = json.loads(PROGRAM_FILE.read_text())
        print(json.dumps(route(args.issue, programs), indent=2))
