"""The component contract — verifier, scorecard, agent_card.

Every bot spec carries three things that make it a *component* rather than a
prompt: a verifier that proves the work happened, a scorecard that decides
whether to keep the bot, and an AgentCard that lets other agents find it.

Everything here is a pure function of the spec. No clock, no model, no DB read,
so spec_hash stays a stable digest of the contract.
"""

from __future__ import annotations

import hashlib
import json

CONTRACT_VERSION = "1.0.0"

#: The measurement inputs decide() reads. Names only, never values — build_scorecard()
#: must stay a pure function of the spec so spec_hash stays stable.
SCORECARD_INPUTS = ("runs", "successes", "failures", "revenue_usd", "cost_usd")

#: The threshold keys decide() consults. Names, not values: active_rule() reads the
#: database, and calling it here would make spec_hash depend on external state.
SCORECARD_THRESHOLD_KEYS = (
    "kill_success_rate_below",
    "kill_net_usd_below",
    "kill_runs_min",
    "kill_roi_below",
    "keep_success_rate_min",
    "keep_net_usd_above",
    "keep_runs_min",
)


def _known_threshold_keys():
    """The live threshold keys from the decision engine.

    Lazy import: contract.py must not import measurement at module load. Loud on
    failure — a gate that cannot see the engine must not pass silently.
    """
    from orchestrator import measurement
    return set(measurement.THRESHOLDS)

REQUIRED_VERIFIER_CHECKS = ("outputs_present", "no_silent_green", "citations_resolve")

REQUIRED_AGENT_CARD_KEYS = ("name", "description", "version", "capabilities", "skills")


def _canonical(obj):
    """Canonical JSON: sorted keys, no whitespace."""
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def _digest(obj):
    return hashlib.sha256(_canonical(obj).encode("utf-8")).hexdigest()


def _bot_id(spec):
    return spec.get("id") or spec.get("bot_id") or "unknown"


def build_verifier(spec):
    """The checks that prove the bot did its job — not that it exited 0."""
    output = spec.get("output") or {}
    expects = sorted(output.keys()) if isinstance(output, dict) else []
    return {
        "version": CONTRACT_VERSION,
        "bot_id": _bot_id(spec),
        "checks": [
            {
                "id": "outputs_present",
                "kind": "assertion",
                "detail": "the run produced the declared output keys",
                "expects": expects,
            },
            {
                "id": "no_silent_green",
                "kind": "assertion",
                "detail": "a run must write a result or state an explicit no-op reason",
                "expects": "result_written or no_op_reason",
            },
            {
                "id": "citations_resolve",
                "kind": "assertion",
                "detail": "every citation in the run still resolves",
                "expects": "all_citations_resolve",
            },
        ],
        "on_fail": "fail_loud",
        "ledger_events": {"pass": "bot.run.verified", "fail": "bot.run.failed"},
    }


def build_scorecard(spec, min_measurements=1):
    """The keep/kill eval harness — a POINTER to the engine that actually decides.

    This does not define a rule. orchestrator.measurement.decide() owns the rule;
    this declares which inputs it reads and which threshold keys it consults, so a
    spec can be checked against the live engine without duplicating it.

    Pure: no database read, no active_rule() call. Same spec in -> same bytes out.
    """
    return {
        "version": CONTRACT_VERSION,
        "bot_id": _bot_id(spec),
        "kind": "keep_or_kill",
        "verdict_rule": "delegated to orchestrator.measurement.decide() — see threshold_keys",
        "evaluated_by": "orchestrator.measurement.decide",
        "rule_version_source": "orchestrator.measurement.active_rule()",
        "reads": list(SCORECARD_INPUTS),
        "threshold_keys": list(SCORECARD_THRESHOLD_KEYS),
        "min_measurements": int(min_measurements),
        "on_kill": "retire_and_record_reason",
    }


def build_agent_card(spec):
    """A2A v1.0 shape. Deliberately does not embed spec_hash — that would be circular."""
    steps = spec.get("steps") or []
    skills = []
    for i, step in enumerate(steps):
        if isinstance(step, dict):
            skills.append({
                "id": step.get("id") or "step-%d" % (i + 1),
                "name": step.get("action") or step.get("name") or "step",
                "description": step.get("detail", ""),
            })
    if not skills:
        skills = [{
            "id": "run",
            "name": spec.get("role") or "run",
            "description": "run the bot's declared job",
        }]
    allowed = spec.get("allowed_actions") or []
    return {
        "a2a_version": "1.0",
        "name": spec.get("name") or _bot_id(spec),
        "description": spec.get("role") or "",
        "version": spec.get("version") or "1.0.0",
        "capabilities": {"streaming": False, "push_notifications": False},
        "skills": skills,
        "input_modes": ["application/json"],
        "output_modes": ["application/json"],
        "security": {
            "allowlist": list(allowed),
            "denylist": [],
            "requires_human_approval": bool(allowed),
        },
    }


def attach_contract(spec, min_measurements=1):
    """Return a copy of the spec carrying the three contract fields."""
    out = dict(spec)
    out["verifier"] = build_verifier(spec)
    out["scorecard"] = build_scorecard(spec, min_measurements)
    out["agent_card"] = build_agent_card(spec)
    return out


def contract_gaps(spec):
    """Every reason this spec is not yet a component. Empty list == complete."""
    if not isinstance(spec, dict):
        return ["spec is not a dict"]
    gaps = []

    verifier = spec.get("verifier")
    if not isinstance(verifier, dict):
        gaps.append("verifier missing")
    else:
        ids = {c.get("id") for c in verifier.get("checks", []) if isinstance(c, dict)}
        for need in REQUIRED_VERIFIER_CHECKS:
            if need not in ids:
                gaps.append("verifier missing check %r" % need)
        if verifier.get("on_fail") != "fail_loud":
            gaps.append("verifier.on_fail must be 'fail_loud' (got %r)" % (verifier.get("on_fail"),))

    scorecard = spec.get("scorecard")
    if not isinstance(scorecard, dict):
        gaps.append("scorecard missing")
    else:
        if not scorecard.get("verdict_rule"):
            gaps.append("scorecard.verdict_rule missing")
        if not isinstance(scorecard.get("min_measurements"), int):
            gaps.append("scorecard.min_measurements missing")
        keys = scorecard.get("threshold_keys")
        if not isinstance(keys, list) or not keys:
            gaps.append("scorecard.threshold_keys missing")
        else:
            known = _known_threshold_keys()
            for key in keys:
                if key not in known:
                    gaps.append("scorecard names an unknown threshold: %s" % key)


    card = spec.get("agent_card")
    if not isinstance(card, dict):
        gaps.append("agent_card missing")
    else:
        for key in REQUIRED_AGENT_CARD_KEYS:
            if key not in card:
                gaps.append("agent_card missing %r" % key)

    return gaps
