"""Typed handoff between agents. Chat paste is not a contract."""

from __future__ import annotations

REQUIRED = (
    "goal",
    "constraints",
    "evidence",
    "open_questions",
    "authority",
    "done_when",
)


def make_handoff(*, goal, constraints, evidence, open_questions, authority, done_when):
    obj = {
        "goal": goal,
        "constraints": list(constraints),
        "evidence": list(evidence),
        "open_questions": list(open_questions),
        "authority": list(authority),
        "done_when": done_when,
    }
    validate_handoff(obj)
    return obj


def validate_handoff(obj):
    if not isinstance(obj, dict):
        raise TypeError("handoff must be an object")
    missing = [key for key in REQUIRED if key not in obj]
    if missing:
        raise ValueError("handoff missing: " + ", ".join(missing))
    if not isinstance(obj["evidence"], list):
        raise TypeError("evidence must be a list")
    for item in obj["evidence"]:
        if not isinstance(item, dict) or "id" not in item or "quote" not in item:
            raise ValueError("each evidence item needs id and quote")
    if not isinstance(obj["authority"], list):
        raise TypeError("authority must be a list of allowed actions")
    return obj


def allow(handoff, action: str) -> bool:
    validate_handoff(handoff)
    return action in handoff["authority"]
