#!/usr/bin/env python3
"""Pick a Claude Code or Codex model with a local Laya decision, then start the agent."""
import argparse
import json
import shutil
import subprocess
import sys
import time
from pathlib import Path

import laya

# Edit these maps to match the models your plan or workspace can use.
MODELS = {
    "claude": {"A": "haiku", "B": "sonnet", "C": "opus"},
    "codex": {"A": "gpt-6-luna", "B": "gpt-6.1-sol", "C": "gpt-6-astra"},
}
DEFAULT_TIER = "B"  # used when Laya is unsure

# Opaque A/B/C keys: Laya reads the descriptions, and the README warns
# that yes/no style labels can sway the answer.
QUESTIONS = {
    "tier": {
        "type": "choice",
        "instructions": "Which tier of coding model does `request` need?",
        "criteria": {
            "A": "small and clear: a typo, a rename, or a one-file edit "
                 "with a known cause",
            "B": "routine development: a feature with tests, a code review, "
                 "or a bug that needs reading several files",
            "C": "hard or risky: architecture, concurrency, security, "
                 "data migrations, or changes across services",
        },
    },
    "risk": {
        "type": "choice",
        "instructions": "Could a mistake while doing `request` cause damage?",
        "criteria": {
            "A": "no: a mistake stays local and is easy to undo",
            "B": "yes: a mistake could touch money, auth, secrets, "
                 "user data, or production systems",
        },
    },
}


def confidence(answer):
    value = answer.get("answer_confidence")
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        return float(value)
    return max(answer["probabilities"].values())


def route(router, task, threshold):
    start = time.perf_counter()
    result = router.predict({"request": task}, QUESTIONS)
    elapsed_ms = round((time.perf_counter() - start) * 1000)
    answers = result["answers"]
    tier = answers["tier"]["choice"]
    tier_conf = confidence(answers["tier"])
    risk_p = float(answers["risk"]["probabilities"]["B"])
    if risk_p >= 0.5:
        final, reason = "C", "risk flagged: use the strongest tier"
    elif tier_conf < threshold:
        final, reason = DEFAULT_TIER, "low confidence: use the default tier"
    else:
        final, reason = tier, "selected tier"
    return {
        "laya_tier": tier,
        "tier_confidence": round(tier_conf, 3),
        "risk_probability": round(risk_p, 3),
        "final_tier": final,
        "reason": reason,
        "checkpoint": result["routing"]["model"],
        "decision_ms": elapsed_ms,
    }


def agent_command(agent, model):
    executable = shutil.which(agent)
    if not executable:
        raise ValueError(f"{agent} is not on PATH.")
    if agent == "claude":
        # Print mode, plan permission mode: Claude reads and plans, no edits.
        return [executable, "-p", "--model", model, "--permission-mode", "plan"]
    # Codex reads the prompt from stdin because of the final "-".
    return [executable, "exec", "--model", model, "--sandbox", "read-only", "-"]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("task_file", type=Path)
    parser.add_argument("--agent", choices=sorted(MODELS), default="claude")
    parser.add_argument("--run", action="store_true",
                        help="Start a read-only agent run with the chosen model.")
    parser.add_argument("--threshold", type=float, default=0.5)
    parser.add_argument("--device", default=None, help="cpu, cuda, mps, or xpu")
    args = parser.parse_args()
    if not 0 <= args.threshold <= 1:
        parser.error("--threshold must be between 0 and 1.")
    task = args.task_file.read_text(encoding="utf-8").strip()
    if not task:
        parser.error("The task file is empty.")

    router = laya.Router(device=args.device)
    decision = route(router, task, args.threshold)
    decision["agent"] = args.agent
    decision["model"] = MODELS[args.agent][decision["final_tier"]]
    print(json.dumps(decision, indent=2), flush=True)

    if args.run:
        # The task goes through stdin. No shell command is built from it.
        command = agent_command(args.agent, decision["model"])
        return subprocess.run(command, input=task, text=True, check=False).returncode
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (KeyError, OSError, ValueError) as error:
        print(f"Stopped: {error}", file=sys.stderr)
        sys.exit(1)
