#!/usr/bin/env python3
"""Authored fallback fixtures, Python 3.9+ standard library. Zero provider/model calls.

Independent API: route(runtime, request, state, event, capabilities) -> decision dict.
The grader exercises actual learner code and checks fixture calls/ledger. No general
routing implementation is provided; scaffold is unfinished. Guided code is one case.
"""
import argparse
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import platform
import subprocess
import sys

# CLI runtime and learner imports share one canonical module and exported types.
if __name__ == "__main__":
    sys.modules["fallback_lab"] = sys.modules[__name__]


class RoutingRuntime:
    def __init__(self, now=0, ledger=None, fallback_event=None):
        self.now = now
        self.ledger = copy.deepcopy(ledger or [])
        self.calls = []
        self.fallback_event = copy.deepcopy(fallback_event or {"kind": "draft", "text": "fixture draft"})

    def wait(self, units):
        if type(units) is not int or units < 0:
            raise ValueError("invalid_wait")
        self.now += units
        self.calls.append({"action": "wait", "units": units})

    def call_fallback(self, business_id, facts):
        self.calls.append({"action": "fallback", "business_id": business_id, "facts": copy.deepcopy(facts)})
        return copy.deepcopy(self.fallback_event)

    def lookup(self, business_id):
        self.calls.append({"action": "lookup", "business_id": business_id})
        matches = [r for r in self.ledger if r["business_id"] == business_id]
        return copy.deepcopy(matches[-1]) if matches else None

    def submit_write(self, business_id):
        """Deliberately non-idempotent fixture to expose replay; not a real external write."""
        receipt = {"business_id": business_id, "receipt_id": "receipt-" + str(len(self.ledger) + 1), "status": "committed"}
        self.calls.append({"action": "write", "business_id": business_id})
        self.ledger.append(receipt)
        return copy.deepcopy(receipt)

    def audit(self):
        return {"now": self.now, "calls": self.calls, "ledger": self.ledger}


REQUEST = {"business_id": "biz-77", "required_caps": ["tools", "json"], "deadline": 5, "max_model_calls": 2}
FACTS = [{"kind": "tool_result", "operation_id": "read-op-1", "data": "confirmed"}]
STATE = {"business_id": "biz-77", "write_state": "none", "receipt": None, "facts": FACTS, "used_calls": 1}
EVENT = {"kind": "rate_limited", "http_status": 429, "wait_units": 2}
RECEIPT = {"business_id": "biz-77", "receipt_id": "receipt-1", "status": "committed"}
TEMPLATE = '''def route(runtime, request, state, event, capabilities):
    """Return business_id/status/receipt/facts/reason/draft, with exactly those keys.
    Validate IDs and strict integer budgets before actions (bool is invalid).
    Preserve completed/unknown writes before considering another model call.
    Only the authored rate_limited/429 fixture permits fallback, at most once.
    No branch of this routing exercise may call submit_write.
    Return draft_ready for a fixture draft; it does not mean business completion.
    """
    raise NotImplementedError("implement route")
'''


def decision(request, state, status, reason, receipt=None, draft=None):
    return {"business_id": request["business_id"], "status": status, "receipt": receipt,
            "facts": copy.deepcopy(state["facts"]), "reason": reason, "draft": draft}


def case_data(name):
    req, state, event, caps = copy.deepcopy(REQUEST), copy.deepcopy(STATE), copy.deepcopy(EVENT), ["tools", "json"]
    now, ledger, fallback_event = 0, [], None
    status, reason, receipt, draft, actions = "draft_ready", "fallback_draft", None, "fixture draft", ["wait", "fallback"]
    if name == "invalid_parameters":
        event = {"kind": "invalid_parameters", "http_status": 400}
        status, reason, draft, actions = "permanent_error", "invalid_parameters", None, []
    elif name == "capability_missing":
        caps = ["tools"]
        status, reason, draft, actions = "capability_blocked", "missing:json", None, []
    elif name == "committed":
        state.update(write_state="committed", receipt=copy.deepcopy(RECEIPT))
        ledger = [copy.deepcopy(RECEIPT)]
        status, reason, receipt, draft, actions = "committed", "existing_receipt", copy.deepcopy(RECEIPT), None, []
    elif name in ("unknown_found", "unknown_missing"):
        state["write_state"] = "unknown"
        actions, draft = ["lookup"], None
        if name == "unknown_found":
            ledger = [copy.deepcopy(RECEIPT)]
            status, reason, receipt = "committed", "reconciled_receipt", copy.deepcopy(RECEIPT)
        else:
            status, reason = "reconcile_required", "receipt_not_found_is_not_proof_of_no_write"
    elif name in ("permission_denied", "safety_refusal"):
        event = {"kind": name}
        status, reason, draft, actions = "denied", name, None, []
    elif name == "deadline_exceeded":
        now = 4
        status, reason, draft, actions = "deadline_exceeded", "backoff_exceeds_remaining_time", None, []
    elif name == "budget_exhausted":
        state["used_calls"] = 2
        status, reason, draft, actions = "budget_exhausted", "model_call_budget_exhausted", None, []
    elif name == "fallback_unavailable":
        fallback_event = {"kind": "unavailable", "http_status": 429}
        status, reason, draft = "paused", "fallback_unavailable", None
    elif name == "changed_input":
        req["business_id"] = state["business_id"] = "order-909"
        state["facts"] = [{"kind": "tool_result", "operation_id": "stock-check-9", "data": {"quantity": 4}}]
        caps = ["json", "unused", "tools"]
        event["wait_units"] = 1
    elif name == "at_deadline":
        now = 3
    elif name == "other_failure":
        event = {"kind": "transport_error"}
        status, reason, draft, actions = "paused", "unsupported_failure", None, []
    elif name == "bool_budget":
        req["max_model_calls"] = True
        actions = []
    elif name == "mismatched_business_id":
        state["business_id"] = "wrong-business"
        actions = []
    elif name == "bool_deadline":
        req["deadline"] = True
        actions = []
    expected = decision(req, state, status, reason, receipt, draft)
    return req, state, event, caps, now, ledger, fallback_event, expected, actions


CASES = ["rate_limited", "invalid_parameters", "capability_missing", "committed", "unknown_found",
         "unknown_missing", "permission_denied", "safety_refusal", "deadline_exceeded", "budget_exhausted",
         "fallback_unavailable", "changed_input", "at_deadline", "other_failure", "bool_budget",
         "mismatched_business_id", "bool_deadline"]


def load_learner(path):
    spec = importlib.util.spec_from_file_location("learner_under_test", path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module.route


def grade_case(path, name):
    req, state, event, caps, now, ledger, fallback_event, expected, actions = case_data(name)
    originals = copy.deepcopy([req, state, event, caps])
    rt = RoutingRuntime(now, ledger, fallback_event)
    result, caught, errors = None, None, []
    try:
        result = load_learner(path)(rt, req, state, event, caps)
    except BaseException as exc:
        caught = exc
    invalid = name in ("bool_budget", "mismatched_business_id", "bool_deadline")
    if invalid:
        if not isinstance(caught, ValueError) or rt.calls:
            errors.append("invalid_input_must_raise_before_actions")
    else:
        if caught:
            errors.append("unexpected_exception:" + type(caught).__name__ + ":" + str(caught))
        if result != expected:
            errors.append("decision_contract_mismatch")
        actual_actions = [c["action"] for c in rt.calls]
        if actual_actions != actions:
            errors.append("actual_call_sequence_mismatch")
        expected_now = now + (event["wait_units"] if "wait" in actions else 0)
        if rt.now != expected_now or rt.now > req["deadline"]:
            errors.append("shared_time_budget_mismatch")
        for call in rt.calls:
            if call["action"] in ("fallback", "lookup", "write") and call["business_id"] != req["business_id"]:
                errors.append("business_id_changed")
            if call["action"] == "fallback" and call["facts"] != originals[1]["facts"]:
                errors.append("executed_facts_lost_or_changed")
            if call["action"] == "wait" and call["units"] != event["wait_units"]:
                errors.append("authored_backoff_policy_not_followed")
        fallback_count = sum(c["action"] == "fallback" for c in rt.calls)
        if state["used_calls"] + fallback_count > req["max_model_calls"]:
            errors.append("model_call_budget_exceeded")
    if rt.ledger != ledger or any(c["action"] == "write" for c in rt.calls):
        errors.append("routing_replayed_or_created_write")
    if [req, state, event, caps] != originals:
        errors.append("input_was_mutated")
    return {"case": name, "pass": not errors, "errors": errors, "result": result,
            "exception": None if caught is None else type(caught).__name__ + ":" + str(caught), "audit": rt.audit()}


def guided(variant="reference"):
    # Each walkthrough is fixed; neither implements the general learner route().
    req, state = copy.deepcopy(REQUEST), copy.deepcopy(STATE)
    if variant == "reference":
        rt = RoutingRuntime()
        rt.wait(2)
        response = rt.call_fallback(req["business_id"], state["facts"])
        result = decision(req, state, "draft_ready", "fallback_draft", draft=response["text"])
        checks = {"same_business_id": result["business_id"] == "biz-77",
                  "facts_preserved": rt.calls[-1]["facts"] == FACTS, "no_write": not rt.ledger,
                  "bounded_calls": len([c for c in rt.calls if c["action"] == "fallback"]) == 1}
    else:
        state.update(write_state="committed", receipt=copy.deepcopy(RECEIPT))
        rt = RoutingRuntime(ledger=[RECEIPT])
        if variant == "broken":
            rt.submit_write("biz-77-retry")  # Deliberate reset/replay after a 429 fixture.
            response = rt.call_fallback("biz-77-retry", [])
            result = decision(req, state, "draft_ready", "fallback_draft", draft=response["text"])
        else:
            result = decision(req, state, "committed", "existing_receipt", receipt=state["receipt"])
        checks = {"one_effect": len(rt.ledger) == 1,
                  "same_receipt": result["receipt"] == RECEIPT,
                  "no_new_model_or_write": not rt.calls,
                  "facts_preserved": result["facts"] == FACTS}
    return {"scenario": "guided_429" if variant == "reference" else "guided_committed_then_429",
            "time_basis": "integer_logical_time", "provider_calls": 0, "variant": variant,
            "checks": checks, "pass": all(checks.values()), "result": result, "audit": rt.audit()}


def grade(path):
    cases = []
    for name in CASES:
        try:
            run = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--mode", "grade-case",
                                  "--learner", str(Path(path).resolve()), "--case", name],
                                 text=True, capture_output=True, timeout=5)
            row = json.loads(run.stdout.splitlines()[-1])
            row["worker_exit_code"] = run.returncode
            if run.returncode != (0 if row.get("pass") else 1):
                row["pass"] = False
                row["errors"].append("worker_exit_code_mismatch")
        except (subprocess.TimeoutExpired, ValueError, IndexError) as exc:
            row = {"case": name, "pass": False, "errors": ["worker_failed:" + type(exc).__name__]}
        cases.append(row)
    return {"mode": "grade", "time_basis": "integer_logical_time", "provider_calls": 0,
            "worker_timeout_seconds": 5, "worker_timeout_purpose": "hang_guard_not_performance_gate",
            "python": platform.python_version(), "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            "learner_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(),
            "module_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(), "module_path": str(Path(path).resolve()),
            "passed": sum(c["pass"] for c in cases), "total": len(cases),
            "pass": all(c["pass"] for c in cases), "cases": cases}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("command", nargs="?", choices=["guided", "scaffold", "incident", "explain", "grade"])
    parser.add_argument("--mode", choices=["reference", "template", "debug", "grade", "grade-case"])
    parser.add_argument("--variant", choices=["broken", "repaired"], default="broken")
    parser.add_argument("--learner", "--module", dest="learner")
    parser.add_argument("--case", choices=CASES)
    parser.add_argument("--out")
    args = parser.parse_args()
    modes = {"guided": "reference", "scaffold": "template", "incident": "debug", "explain": "debug", "grade": "grade"}
    if args.command:
        if args.mode:
            parser.error("use a command or --mode, not both")
        args.mode = modes[args.command]
        if args.command == "explain":
            args.variant = "repaired"
    if args.mode is None:
        parser.error("choose guided/scaffold/incident/explain/grade")
    if args.mode == "template":
        if not args.out:
            parser.error("template requires --out")
        path = Path(args.out)
        if path.exists():
            parser.error("refusing to overwrite learner file")
        path.write_text(TEMPLATE, encoding="utf-8")
        result = {"mode": "template", "path": str(path), "pass": True}
    elif args.mode in ("reference", "debug"):
        result = guided("reference" if args.mode == "reference" else args.variant)
    else:
        if not args.learner or (args.mode == "grade-case" and not args.case):
            parser.error("grade requires --learner; grade-case also requires --case")
        result = grade_case(args.learner, args.case) if args.mode == "grade-case" else grade(args.learner)
    output = json.dumps(result, ensure_ascii=False, sort_keys=True)
    if args.out and args.mode != "template":
        Path(args.out).write_text(output + "\n", encoding="utf-8")
    print(output)
    return 0 if result["pass"] else 1


if __name__ == "__main__":
    sys.exit(main())
