"""Offline fixtures for K05.01.04. Times are virtual milliseconds."""

import json
import sys
from collections import deque
from dataclasses import dataclass, replace


@dataclass(frozen=True)
class Approval:
    tenant: str
    actor: str
    operation_id: str
    city: str
    slot: str
    expires_at_ms: int
    approved: bool = True


@dataclass(frozen=True)
class Context:
    tenant: str
    actor: str
    operation_id: str
    call_id: str
    permissions: frozenset[str]
    approval: Approval | None = None


class ToolError(Exception):
    def __init__(self, code, next_action):
        self.code = code
        self.next_action = next_action


def unique_keys(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate object name")
        result[key] = value
    return result


def reject_constant(_value):
    raise ValueError("non-JSON constant")


def validate(raw, required):
    try:
        args = json.loads(raw, object_pairs_hook=unique_keys, parse_constant=reject_constant)
    except (ValueError, RecursionError):
        raise ToolError("invalid_json", "correct_arguments") from None
    if (
        not isinstance(args, dict)
        or args.keys() != required
        or any(type(value) is not str for value in args.values())
    ):
        raise ToolError("invalid_arguments", "correct_arguments")
    if args["city"] != "Beijing":
        raise ToolError("unsupported_city", "correct_arguments")
    if "slot" in required and args["slot"] not in {"09:00", "10:00"}:
        raise ToolError("unsupported_slot", "correct_arguments")
    return args


class MockBackend:
    def __init__(self, readings=(), *, drop_booking_reply=False):
        self.readings = deque(readings)
        self.drop_booking_reply = drop_booking_reply
        self.now_ms = 0
        self.weather_attempts = 0
        self.booking_attempts = 0
        # One fixture entry is both the observable effect and the dedup record.
        self.bookings = {}

    def weather(self, limit_ms):
        self.weather_attempts += 1
        duration_ms, value = self.readings.popleft()
        self.now_ms += min(duration_ms, limit_ms)
        if duration_ms > limit_ms:
            raise TimeoutError
        return value

    def booking(self, key, payload, limit_ms):
        self.booking_attempts += 1
        if key in self.bookings:
            previous_payload, booking_id = self.bookings[key]
            if previous_payload != payload:
                raise ToolError("idempotency_conflict", "review_intent")
            self.now_ms += 1
            return booking_id, True
        booking_id = f"toy-booking-{len(self.bookings) + 1}"
        self.bookings[key] = (payload, booking_id)
        if self.drop_booking_reply:
            self.drop_booking_reply = False
            self.now_ms += limit_ms
            raise TimeoutError
        self.now_ms += 80
        return booking_id, False


class Executor:
    REQUIRED = {
        "get_weather": {"city"},
        "reserve_weather_briefing": {"city", "slot"},
    }

    def __init__(self, backend, *, budget_ms=350):
        self.backend = backend
        self.budget_ms = budget_ms
        self.events = []

    def record(self, context, tool, phase, code, attempt, started_ms):
        self.events.append({
            "operation_id": context.operation_id,
            "call_id": context.call_id,
            "tool": tool if tool in self.REQUIRED else "unknown_tool",
            "phase": phase,
            "code": code,
            "attempt": attempt,
            "elapsed_ms": self.backend.now_ms - started_ms,
        })

    def dispatch(self, name, raw, context):
        start = self.backend.now_ms
        try:
            if name not in self.REQUIRED:
                raise ToolError("unknown_tool", "choose_supported_tool")
            args = validate(raw, self.REQUIRED[name])
            if name not in context.permissions:
                raise ToolError("permission_denied", "stop")
            deadline = start + self.budget_ms
            if name == "get_weather":
                data = self.read_weather(context, name, args, deadline)
            else:
                data = self.reserve(context, name, args, deadline)
        except ToolError as error:
            self.record(context, name, "result", error.code, None, start)
            return {"ok": False, "error": {"code": error.code, "next_action": error.next_action}}
        self.record(context, name, "result", "ok", None, start)
        return {"ok": True, "data": data}

    def read_weather(self, context, name, args, deadline):
        for attempt in (1, 2):
            start = self.backend.now_ms
            remaining = deadline - start
            if remaining <= 0:
                break
            try:
                value = self.backend.weather(min(200, remaining))
            except TimeoutError:
                self.record(context, name, "attempt", "read_timeout", attempt, start)
                if attempt == 1 and deadline - self.backend.now_ms > 25:
                    self.backend.now_ms += 25
                    continue
                break
            if type(value) is not int:
                self.record(context, name, "attempt", "invalid_tool_output", attempt, start)
                raise ToolError("invalid_tool_output", "inspect_tool")
            self.record(context, name, "attempt", "ok", attempt, start)
            return {"city": args["city"], "temperature": value, "unit": "C", "source": "toy_fixture"}
        raise ToolError("read_timeout", "report_unavailable")

    def reserve(self, context, name, args, deadline):
        approval = context.approval
        if approval is None:
            raise ToolError("approval_required", "request_approval")
        key = (context.tenant, context.actor, context.operation_id)
        payload = (args["city"], args["slot"])
        approved_key = (approval.tenant, approval.actor, approval.operation_id)
        approved_payload = (approval.city, approval.slot)
        if key != approved_key or payload != approved_payload:
            raise ToolError("approval_mismatch", "request_approval")
        if not approval.approved:
            raise ToolError("approval_denied", "stop")
        start = self.backend.now_ms
        if start >= approval.expires_at_ms:
            raise ToolError("approval_expired", "request_approval")
        limit = min(200, deadline - start)
        # The booking fixture needs 80 ms to commit.
        if limit < 80:
            raise ToolError("budget_exhausted", "report_unavailable")
        try:
            booking_id, replay = self.backend.booking(key, payload, limit)
        except TimeoutError:
            self.record(context, name, "attempt", "reply_timeout", 1, start)
            raise ToolError("write_outcome_unknown", "reconcile_same_operation") from None
        except ToolError as error:
            self.record(context, name, "attempt", error.code, 1, start)
            raise
        self.record(context, name, "attempt", "dedup_hit" if replay else "ok", 1, start)
        return {"booking_id": booking_id, "city": args["city"], "slot": args["slot"]}


def run_checks():
    weather = "get_weather"
    reserve = "reserve_weather_briefing"
    beijing = '{"city":"Beijing"}'
    briefing = '{"city":"Beijing","slot":"09:00"}'
    changed = '{"city":"Beijing","slot":"10:00"}'
    original = Context("tenant-demo", "user-demo", "intent-01", "call-01", frozenset({weather, reserve}))
    read_context = replace(original, operation_id="query-01", call_id="call-weather")
    approval = Approval("tenant-demo", "user-demo", "intent-01", "Beijing", "09:00", 1000)
    approved = replace(original, approval=approval)
    passed = 0

    def check(label, condition, detail):
        nonlocal passed
        if not condition:
            raise AssertionError(label)
        passed += 1
        print(f"PASS {label} {detail}")

    rejected_backend = MockBackend()
    rejected = Executor(rejected_backend)
    for label, name, raw, context, expected in (
        ("unknown", "made_up_name", beijing, original, "unknown_tool"),
        ("syntax", weather, '{"city":', original, "invalid_json"),
        ("duplicate_member", weather, '{"city":"Beijing","city":"Beijing"}', original, "invalid_json"),
        ("non_json_constant", weather, '{"city":NaN}', original, "invalid_json"),
        ("shape_type", weather, '{"city":3}', original, "invalid_arguments"),
        ("shape_extra", weather, '{"city":"Beijing","approved":true}', original, "invalid_arguments"),
        ("shape_missing", weather, '{}', original, "invalid_arguments"),
        ("business_city", weather, '{"city":"Somewhere"}', original, "unsupported_city"),
        ("business_slot", reserve, '{"city":"Beijing","slot":"12:00"}', original, "unsupported_slot"),
        ("permission", reserve, briefing, replace(approved, permissions=frozenset()), "permission_denied"),
        ("approval_required", reserve, briefing, original, "approval_required"),
        ("approval_denied", reserve, briefing, replace(approved, approval=replace(approval, approved=False)), "approval_denied"),
        ("approval_changed_payload", reserve, changed, approved, "approval_mismatch"),
        ("approval_wrong_actor", reserve, briefing, replace(approved, actor="other-user"), "approval_mismatch"),
        ("approval_expired", reserve, briefing, replace(approved, approval=replace(approval, expires_at_ms=0)), "approval_expired"),
    ):
        result = rejected.dispatch(name, raw, context)
        check(label, not result["ok"] and result["error"]["code"] == expected, expected)
    check("no_attempt_after_rejection",
          rejected_backend.weather_attempts == rejected_backend.booking_attempts == len(rejected_backend.bookings) == 0,
          "attempts=0 bookings=0")

    reads = MockBackend([(40, 21)])
    executor = Executor(reads)
    result = executor.dispatch(weather, beijing, read_context)
    check("weather_success",
          result == {"ok": True, "data": {"city": "Beijing", "temperature": 21, "unit": "C", "source": "toy_fixture"}},
          "Beijing 21 C fixture ms=40")
    reads = MockBackend([(240, 21), (40, 21)])
    retry = Executor(reads)
    result = retry.dispatch(weather, beijing, read_context)
    check("weather_retry", result["ok"] and reads.weather_attempts == 2 and reads.now_ms == 265,
          "attempts=2 total_ms=200+25+40=265")
    reads = MockBackend([(240, 21), (140, 21)])
    exhausted = Executor(reads)
    result = exhausted.dispatch(weather, beijing, read_context)
    check("weather_budget",
          result == {"ok": False, "error": {"code": "read_timeout", "next_action": "report_unavailable"}}
          and reads.weather_attempts == 2 and reads.now_ms == 350,
          "attempts=2 total_ms=200+25+125=350")
    reads = MockBackend([(240, 21), (40, 21)])
    no_time = Executor(reads, budget_ms=225)
    result = no_time.dispatch(weather, beijing, read_context)
    check("weather_skip_retry", not result["ok"] and reads.weather_attempts == 1 and reads.now_ms == 200,
          "attempts=1 remaining_ms=25 backoff_ms=25")
    reads = MockBackend([(40, "21")])
    result = Executor(reads).dispatch(weather, beijing, read_context)
    check("weather_invalid_output", result["error"]["code"] == "invalid_tool_output" and reads.weather_attempts == 1,
          "string temperature rejected")

    writes = MockBackend(drop_booking_reply=True)
    executor = Executor(writes)
    result = executor.dispatch(reserve, briefing, approved)
    check("write_timeout_after_commit",
          result == {"ok": False, "error": {
              "code": "write_outcome_unknown", "next_action": "reconcile_same_operation"
          }} and len(writes.bookings) == writes.booking_attempts == 1,
          "attempts=1 bookings_in_memory=1")
    result = executor.dispatch(reserve, briefing, replace(approved, call_id="call-replay"))
    check("write_reconcile_same_operation",
          result["ok"] and result["data"]["booking_id"] == "toy-booking-1"
          and writes.booking_attempts == 2 and len(writes.bookings) == 1,
          "new call_id same operation_id same booking bookings=1")
    modified = replace(approved, approval=replace(approval, slot="10:00"), call_id="call-modified")
    result = executor.dispatch(reserve, changed, modified)
    check("write_same_key_changed_intent",
          result["error"]["code"] == "idempotency_conflict" and len(writes.bookings) == 1,
          "changed payload rejected bookings=1")
    new_intent = replace(approved, operation_id="intent-02",
                         approval=replace(approval, operation_id="intent-02"), call_id="call-new")
    result = executor.dispatch(reserve, briefing, new_intent)
    check("write_identical_payload_new_intent",
          result["ok"] and result["data"]["booking_id"] == "toy-booking-2" and len(writes.bookings) == 2,
          "same payload distinct authorized operation bookings=2")
    result = Executor(writes, budget_ms=79).dispatch(reserve, briefing, approved)
    check("write_budget_before_attempt", result["error"]["code"] == "budget_exhausted" and writes.booking_attempts == 4,
          "no backend attempt")

    check("observable_trace",
          [event["code"] for event in retry.events] == ["read_timeout", "ok", "ok"]
          and [event["code"] for event in executor.events[:4]] == [
              "reply_timeout", "write_outcome_unknown", "dedup_hit", "ok"
          ]
          and all(set(event) == {"operation_id", "call_id", "tool", "phase", "code", "attempt", "elapsed_ms"}
                  for event in retry.events + executor.events),
          "attempt vs result codes and selected fields")
    for event in retry.events + executor.events[:4]:
        print("TRACE", json.dumps(event, sort_keys=True))
    print(f"PASS total={passed} python={sys.version.split()[0]}")


if __name__ == "__main__":
    run_checks()
