#!/usr/bin/env python3
"""Illustrative model-exit fixtures. Python 3.10+, standard library, no network.

These reduced, hand-authored envelopes borrow documented field shapes. They are
NOT provider responses, full SDK implementations, a JSON Schema validator, or a
model benchmark. The local contract permits exactly one text or lookup-ticket
outcome. Run: python3 example.py [optional-results-path]
"""
from __future__ import annotations

from collections import Counter
from copy import deepcopy
import hashlib
import json
from pathlib import Path
import sys


def result(outcome, reason=None, **fields):
    return {"outcome": outcome, **({"reason": reason} if reason else {}), **fields}


def finish(kind, payload):
    """Application contract, deliberately narrower than either provider API."""
    if kind == "answer":
        if not isinstance(payload, str) or not payload.strip():
            return result("blocked", "empty_or_invalid_text")
        return result("answer", text=payload)
    if kind == "refused":
        return result("refused")
    if kind != "tool":
        return result("blocked", "unknown_content_type")
    name, call_id, arguments = payload
    if name != "lookup_ticket":
        return result("blocked", "tool_not_allowed")
    if not isinstance(call_id, str) or not call_id.strip():
        return result("blocked", "missing_call_id")
    if not isinstance(arguments, dict):
        return result("blocked", "argument_shape")
    if set(arguments) != {"ticket_id"}:
        return result("blocked", "argument_fields")
    if not isinstance(arguments["ticket_id"], str) or not arguments["ticket_id"].strip():
        return result("blocked", "argument_type")
    # Normalizing a tool request never executes or authorizes the tool.
    return result("tool_request", name=name, call_id=call_id, arguments=arguments)


def old_adapter(envelope):
    """Reduced Responses-like, non-streaming fixture adapter."""
    status = envelope.get("status")
    if status == "incomplete":
        return result("incomplete")
    if status != "completed":
        return result("blocked", "unknown_or_nonterminal_state")
    output = envelope.get("output", [])
    if not isinstance(output, list) or len(output) != 1:
        return result("blocked", "outcome_cardinality")
    item = output[0]
    if item.get("type") == "function_call":
        raw = item.get("arguments")
        try:
            arguments = json.loads(raw) if isinstance(raw, str) else None
        except json.JSONDecodeError:
            return result("blocked", "argument_shape")
        return finish("tool", (item.get("name"), item.get("call_id"), arguments))
    if item.get("type") != "message":
        return finish("unknown", None)
    if item.get("status") != "completed":
        return result("blocked", "unknown_or_nonterminal_state")
    blocks = item.get("content", [])
    if not isinstance(blocks, list) or len(blocks) != 1:
        return result("blocked", "outcome_cardinality")
    block = blocks[0]
    if block.get("type") == "refusal":
        return finish("refused", None)
    if block.get("type") == "output_text":
        return finish("answer", block.get("text"))
    return finish("unknown", None)


def new_adapter(envelope):
    """Reduced Messages-like, non-streaming fixture adapter."""
    stop = envelope.get("stop_reason")
    if stop in {"max_tokens", "model_context_window_exceeded"}:
        return result("incomplete")
    if stop == "refusal":
        return finish("refused", None)
    if stop not in {"end_turn", "tool_use"}:
        return result("blocked", "unknown_or_nonterminal_state")
    blocks = envelope.get("content", [])
    if not isinstance(blocks, list) or len(blocks) != 1:
        return result("blocked", "outcome_cardinality")
    block = blocks[0]
    if block.get("type") == "tool_use" and stop == "tool_use":
        return finish("tool", (block.get("name"), block.get("id"), block.get("input")))
    if block.get("type") == "text" and stop == "end_turn":
        return finish("answer", block.get("text"))
    return finish("unknown", None)


def shortcut_new_adapter(envelope):
    """Intentionally incomplete field-renaming shortcut; not a vendor adapter."""
    block = envelope.get("content", [{}])[0]
    if block.get("type") == "tool_use":
        return result("tool_request", name=block.get("name"), call_id=block.get("id"), arguments=block.get("input"))
    return result("answer", text=block.get("text", ""))


def old_text(text="The ticket is awaiting review."):
    return {"status": "completed", "output": [{"type": "message", "status": "completed", "content": [{"type": "output_text", "text": text}]}]}


def new_text(text="The ticket is awaiting review."):
    return {"stop_reason": "end_turn", "content": [{"type": "text", "text": text}]}


def old_tool():
    return {"status": "completed", "output": [{"type": "function_call", "name": "lookup_ticket", "call_id": "call-17", "arguments": '{"ticket_id":"T-17"}'}]}


def new_tool():
    return {"stop_reason": "tool_use", "content": [{"type": "tool_use", "name": "lookup_ticket", "id": "call-17", "input": {"ticket_id": "T-17"}}]}


def fixtures():
    rows = []
    def add(name, family, old, new, expected):
        rows.append({"name": name, "family": family, "old": old, "new": new, "expected": expected})
    add("complete_text", "permitted", old_text(), new_text(), result("answer", text="The ticket is awaiting review."))
    add("permitted_tool", "permitted", old_tool(), new_tool(), result("tool_request", name="lookup_ticket", call_id="call-17", arguments={"ticket_id": "T-17"}))
    old, new = old_text(), new_text("I cannot help with that request.")
    old["output"][0]["content"] = [{"type": "refusal", "refusal": "I cannot help with that request."}]
    new["stop_reason"] = "refusal"
    add("explicit_refusal", "refusal", old, new, result("refused"))
    old, new = old_text("Partial"), new_text("Partial")
    old["status"], new["stop_reason"] = "incomplete", "max_tokens"
    add("output_limit", "incomplete", old, new, result("incomplete"))
    old, new = old_text(), new_text()
    old["status"], new["stop_reason"] = "future_state", "future_stop"
    add("unknown_terminal_state", "unknown", old, new, result("blocked", "unknown_or_nonterminal_state"))
    old, new = old_text(), new_text()
    old["output"][0]["content"][0]["type"] = "future_block"
    new["content"][0]["type"] = "future_block"
    add("unknown_content", "unknown", old, new, result("blocked", "unknown_content_type"))
    for name, field, old_value, new_value, reason in [
        ("malformed_arguments", "arguments", "{broken", [], "argument_shape"),
        ("disallowed_tool", "name", "delete_ticket", "delete_ticket", "tool_not_allowed"),
        ("missing_call_identifier", "call_id", "", "", "missing_call_id"),
        ("wrong_argument_type", "arguments", '{"ticket_id":17}', {"ticket_id": 17}, "argument_type"),
        ("additional_argument", "arguments", '{"ticket_id":"T-17","admin":true}', {"ticket_id": "T-17", "admin": True}, "argument_fields"),
    ]:
        old, new = old_tool(), new_tool()
        old["output"][0][field] = old_value
        new["content"][0][{"arguments": "input", "call_id": "id"}.get(field, field)] = new_value
        add(name, "tool_contract", old, new, result("blocked", reason))
    add("empty_text", "content", old_text(""), new_text(""), result("blocked", "empty_or_invalid_text"))
    old, new = old_tool(), new_tool()
    old["output"].append(deepcopy(old["output"][0]))
    new["content"].append(deepcopy(new["content"][0]))
    add("multiple_tools", "cardinality", old, new, result("blocked", "outcome_cardinality"))
    old, new = old_text(), new_text()
    old["status"], new["stop_reason"] = "in_progress", "pause_turn"
    add("nonterminal_response", "unknown", old, new, result("blocked", "unknown_or_nonterminal_state"))
    return rows


def run():
    rows = fixtures()
    reports = {}
    for name, adapter, field in [("old_contract_adapter", old_adapter, "old"), ("new_shortcut_adapter", shortcut_new_adapter, "new"), ("new_contract_adapter", new_adapter, "new")]:
        observations = [{"case": row["name"], "family": row["family"], "expected": row["expected"], "actual": adapter(deepcopy(row[field]))} for row in rows]
        for item in observations:
            item["passed"] = item["expected"] == item["actual"]
        failures = [x for x in observations if not x["passed"]]
        reports[name] = {"cases": len(rows), "passed": len(rows) - len(failures), "failed": len(failures), "failure_families": dict(sorted(Counter(x["family"] for x in failures).items())), "observations": observations}
    assert reports["old_contract_adapter"]["failed"] == 0
    assert reports["new_contract_adapter"]["failed"] == 0
    assert reports["new_shortcut_adapter"]["passed"] == 2
    for row in rows:
        assert old_adapter(row["old"]) == new_adapter(row["new"])
    # Mutation checks: known regressions must be visible, not merely executable.
    assert new_adapter(new_text("")) != result("answer", text="")
    assert new_adapter({"stop_reason": "future_stop", "content": [{"type": "text", "text": "plausible"}]})["outcome"] == "blocked"
    return {"study_type": "Illustrative deterministic local adapter fixtures; not model or provider measurements", "fixture_cases": len(rows), "adapter_case_evaluations": len(rows) * len(reports), "external_model_calls": 0, "tool_executions": 0, "latency_cost_quality_measured": False, "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "fixture_sha256": hashlib.sha256(json.dumps(rows, sort_keys=True).encode()).hexdigest(), "reports": reports, "limits": ["Hand-authored reduced envelopes; not a complete provider protocol", "Single text block or single tool contract; legitimate richer output is blocked", "No streaming, real provider output, retries, data transfer, billing, model quality or security proof", "No general JSON Schema validator; explicit fields only", "Fixture pass counts cannot establish production failure probabilities"]}


if __name__ == "__main__":
    report = run()
    destination = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name("results.json")
    destination.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
    print(json.dumps({"fixture_cases": report["fixture_cases"], "adapter_case_evaluations": report["adapter_case_evaluations"], "adapters": {name: {key: value[key] for key in ("passed", "failed", "failure_families")} for name, value in report["reports"].items()}}, indent=2))
