"""Local input/output gate. No live model, tool execution or automatic release."""
import argparse
import json
from pathlib import Path
import sys
from typing import Literal

from pydantic import BaseModel, ConfigDict, Field, ValidationError

ROOT = Path(__file__).resolve().parent
DEMO_MARKER = "DEMO_ONLY_SECRET_20261124"
MAX_INPUT_BYTES = 4096
MAX_OUTPUT_BYTES = 8192


class GateError(ValueError):
    pass


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise GateError("duplicate_json_key")
        result[key] = value
    return result


def reject_constant(value):
    raise GateError("non_json_constant")


def parse(raw, limit):
    if len(raw) > limit:
        raise GateError("payload_too_large")
    try:
        return json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object,
                          parse_constant=reject_constant)
    except (UnicodeDecodeError, json.JSONDecodeError, RecursionError) as exc:
        raise GateError("invalid_json") from exc


def read_bytes(name, limit):
    target = (ROOT / name).resolve()
    if target.parent != ROOT or not target.is_file():
        raise GateError("fixture_file_unavailable")
    with target.open("rb") as stream:
        return stream.read(limit + 1)


class Request(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    case_id: str = Field(min_length=1, max_length=48)
    prompt_version: str = Field(min_length=1, max_length=80)
    question: str = Field(min_length=1, max_length=500)


class Evidence(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    source_id: str = Field(min_length=1, max_length=80)
    quote: str = Field(min_length=1, max_length=600)


class Candidate(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    case_id: str = Field(min_length=1, max_length=48)
    prompt_version: str = Field(min_length=1, max_length=80)
    decision: Literal["answer", "clarify", "handoff"]
    answer: str = Field(min_length=1, max_length=1200)
    evidence: list[Evidence] = Field(max_length=4)
    status: Literal["draft"]
    actions: list[dict] = Field(max_length=0)


class Source(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    source_id: str = Field(min_length=1, max_length=80)
    text: str = Field(min_length=1, max_length=2000)


class Context(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    sources: list[Source] = Field(max_length=4)


def run(request_raw, candidate_reader, context_reader):
    events = []

    def event(stage, result):
        events.append({"stage": stage, "result": result})

    def report(code, candidate=None):
        return {"decision": code, "events": events,
                "candidate_for_review": candidate.model_dump() if candidate else None,
                "public_output": None, "release": False, "human_approved": False,
                "semantics_checked": False, "authenticated": False,
                "new_model_calls": 0, "external_writes": 0,
                "secret_check_scope": "known_demo_marker_only"}

    try:
        request = Request.model_validate(parse(request_raw, MAX_INPUT_BYTES))
        if DEMO_MARKER in request.question:
            event("input", "known_demo_marker");return report("input_blocked")
        event("input", "passed")
    except (GateError, ValidationError):
        event("input", "invalid_or_oversized");return report("input_blocked")
    try:
        context = Context.model_validate(parse(context_reader(), MAX_OUTPUT_BYTES))
        sources = {item.source_id: item.text for item in context.sources}
        if len(sources) != len(context.sources):
            raise GateError("duplicate_source_id")
        if not sources:
            event("context", "empty");return report("context_blocked")
        event("context", "loaded_fixture")
    except (GateError, ValidationError, OSError):
        event("context", "unavailable_or_invalid");return report("context_blocked")
    try:
        candidate = Candidate.model_validate(parse(candidate_reader(), MAX_OUTPUT_BYTES))
        event("output_schema", "passed")
    except (GateError, ValidationError, OSError):
        event("output_schema", "invalid_or_unavailable");return report("output_blocked")
    if candidate.case_id != request.case_id or candidate.prompt_version != request.prompt_version:
        event("binding", "case_or_version_mismatch");return report("output_blocked")
    event("binding", "passed")
    if DEMO_MARKER in candidate.answer or any(DEMO_MARKER in item.quote for item in candidate.evidence):
        event("output_marker", "known_demo_marker");return report("output_blocked")
    event("output_marker", "passed_for_known_marker")
    if candidate.decision == "answer" and not candidate.evidence:
        event("evidence", "missing");return report("output_blocked")
    for item in candidate.evidence:
        if item.source_id not in sources:
            event("evidence", "source_not_in_fixture_context");return report("output_blocked")
        if item.quote not in sources[item.source_id]:
            event("evidence", "quote_not_found");return report("output_blocked")
    event("evidence", "reference_and_literal_quote_passed")
    event("release", "manual_review_still_required")
    return report("ready_for_review", candidate)


CASES = ["good", "extra", "no-evidence", "unknown-source", "bad-quote", "action", "sent",
         "marker", "wrong-case", "contradiction", "invalid-json", "long-input"]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("case", choices=CASES)
    parser.add_argument("--no-context", action="store_true")
    args = parser.parse_args()
    request_name = "request-long.json" if args.case == "long-input" else "request.json"
    candidate_name = "candidate-good.json" if args.case == "long-input" else "candidate-" + args.case + ".json"
    try:
        request_raw = read_bytes(request_name, MAX_INPUT_BYTES)
        context_reader = (lambda: b'{"sources":[]}') if args.no_context else lambda: read_bytes("context.json", MAX_OUTPUT_BYTES)
        result = run(request_raw, lambda: read_bytes(candidate_name, MAX_OUTPUT_BYTES), context_reader)
    except (GateError, OSError):
        print(json.dumps({"decision": "fixture_unavailable", "release": False}))
        return 2
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    raise SystemExit(main())
