"""Offline contract replay for K05.01.02; every HTTP request is intercepted."""

from copy import deepcopy
from importlib.metadata import version
import json
from math import exp, isclose
import platform
from typing import Literal

import httpx
from jsonschema import Draft202012Validator, FormatChecker, ValidationError as SchemaError
from openai import BadRequestError, ContentFilterFinishReasonError, LengthFinishReasonError, OpenAI
from pydantic import BaseModel, ConfigDict, ValidationError as TypedParseError


MODEL = "gpt-4o-2024-08-06"
SYSTEM = "Return one JSON object with city, temperature, and unit from the supplied record."
USER = "Weather fixture: Beijing, 21 C."
EXPECTED_CITY = "Beijing"
EXPECTED_UNIT = "C"
ACCEPTED_JSON = '{"city":"Beijing","temperature":21,"unit":"C"}'
MALFORMED_JSON = '{"city":"Beijing","temperature":21,"unit":"C",}'
WRONG_TYPE = '{"city":"Beijing","temperature":"21","unit":"C"}'
WRONG_CITY = '{"city":"Shanghai","temperature":21,"unit":"C"}'
PARTIAL = '{"city":"Beijing"'
SCHEMA = {
    "type": "object",
    "properties": {
        "city": {"type": "string"},
        "temperature": {"type": "number"},
        "unit": {"type": "string", "enum": ["C", "F"]},
    },
    "required": ["city", "temperature", "unit"],
    "additionalProperties": False,
}
LOCAL_SCHEMA = {"$schema": "https://json-schema.org/draft/2020-12/schema", **SCHEMA}
VALIDATOR = Draft202012Validator(LOCAL_SCHEMA)


def unique_members(pairs):
    members = {}
    for key, value in pairs:
        if key in members:
            raise ValueError(f"duplicate key: {key}")
        members[key] = value
    return members


def invalid_constant(value):
    raise ValueError(f"non-JSON numeric literal: {value}")


def validate_weather(text):
    try:
        data = json.loads(text, object_pairs_hook=unique_members, parse_constant=invalid_constant)
    except ValueError:
        return "invalid_json"
    try:
        VALIDATOR.validate(data)
    except SchemaError as error:
        return f"schema:{error.validator}"
    if data["city"] != EXPECTED_CITY or data["unit"] != EXPECTED_UNIT:
        return "business:request_mismatch"
    return "accepted"


def consume_chat(result):
    choice, = result.choices
    if choice.message.refusal is not None:
        return "refusal"
    if choice.finish_reason != "stop":
        return f"finish:{choice.finish_reason}"
    if choice.message.content is None:
        return "missing_text"
    return validate_weather(choice.message.content)


def consume_responses(result):
    parts = [part for item in result.output if item.type == "message" for part in item.content]
    if any(part.type == "refusal" for part in parts):
        return "refusal"
    if result.status == "incomplete" and result.incomplete_details is not None:
        return f"incomplete:{result.incomplete_details.reason}"
    if result.status != "completed":
        return f"status:{result.status}"
    texts = [part.text for part in parts if part.type == "output_text"]
    if len(texts) != 1:
        return "expected_one_text"
    return validate_weather(texts[0])


def chat_reply(text, reason="stop", refusal=None):
    return {
        "id": "chatcmpl_fixture",
        "object": "chat.completion",
        "created": 0,
        "model": MODEL,
        "choices": [{
            "index": 0,
            "finish_reason": reason,
            "message": {"role": "assistant", "content": text, "refusal": refusal},
        }],
    }


def responses_reply(text, status="completed", incomplete_reason=None, refusal=None):
    if refusal is not None:
        parts = [{"type": "refusal", "refusal": refusal}]
    elif text is not None:
        parts = [{"type": "output_text", "text": text, "annotations": []}]
    else:
        parts = []
    return {
        "id": "resp_fixture",
        "object": "response",
        "created_at": 0,
        "model": MODEL,
        "status": status,
        "error": None,
        "incomplete_details": {"reason": incomplete_reason} if incomplete_reason else None,
        "output": [{
            "id": "msg_fixture", "type": "message", "role": "assistant",
            "status": status, "content": parts,
        }],
        "parallel_tool_calls": False,
        "tool_choice": "none",
        "tools": [],
    }


class Weather(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    city: str
    temperature: float
    unit: Literal["C", "F"]


def mock_call(api, mode, reply, *, schema=SCHEMA, status_code=200):
    nested_format = {"name": "beijing_weather", "strict": True, "schema": schema}
    json_mode = {"type": "json_object"}
    chat_format = json_mode if mode == "json" else {"type": "json_schema", "json_schema": nested_format}
    text_format = json_mode if mode == "json" else {"type": "json_schema", **nested_format}
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": USER}]

    def handle(request):
        body = json.loads(request.content)
        assert request.method == "POST" and request.url.host == "fixture.invalid"
        assert body["model"] == MODEL and body["store"] is False
        if api == "chat":
            assert request.url.path == "/v1/chat/completions"
            assert body["messages"] == messages and "text" not in body
            sent = body["response_format"]
        else:
            assert request.url.path == "/v1/responses"
            assert body["input"] == USER and body["instructions"] == SYSTEM
            assert "response_format" not in body
            sent = body["text"]["format"]
        if mode == "typed":
            assert sent["type"] == "json_schema"
            generated = sent["json_schema"] if api == "chat" else sent
            assert generated["strict"] is True and generated["name"] == "Weather"
            assert generated["schema"]["additionalProperties"] is False
            assert generated["schema"]["required"] == list(SCHEMA["properties"])
            assert generated["schema"]["properties"]["unit"]["enum"] == ["C", "F"]
        else:
            assert sent == (chat_format if api == "chat" else text_format)
        return httpx.Response(status_code, json=reply)

    with OpenAI(
        api_key="offline-fixture-key", base_url="https://fixture.invalid/v1",
        max_retries=0, http_client=httpx.Client(transport=httpx.MockTransport(handle)),
    ) as client:
        if api == "chat":
            common = {"model": MODEL, "messages": messages, "store": False}
            if mode == "typed":
                return client.chat.completions.parse(**common, response_format=Weather)
            return client.chat.completions.create(**common, response_format=chat_format)
        common = {"model": MODEL, "input": USER, "instructions": SYSTEM, "store": False}
        if mode == "typed":
            return client.responses.parse(**common, text_format=Weather)
        return client.responses.create(**common, text={"format": text_format})


def check(label, actual, expected):
    assert actual == expected, (label, actual, expected)
    print(f"PASS {label}: {actual}")


def check_raises(label, expected, call):
    try:
        call()
    except expected as error:
        print(f"PASS {label}: {type(error).__name__}")
        return error
    raise AssertionError(f"{label}: {expected.__name__} was not raised")


def check_local_validation():
    Draft202012Validator.check_schema(LOCAL_SCHEMA)
    for label, payload, expected in [
        ("malformed", MALFORMED_JSON, "invalid_json"),
        ("wrong type", WRONG_TYPE, "schema:type"),
        ("wrong city", WRONG_CITY, "business:request_mismatch"),
        ("accepted", ACCEPTED_JSON, "accepted"),
        ("missing", '{"city":"Beijing","temperature":21}', "schema:required"),
        ("extra", ACCEPTED_JSON[:-1] + ',"forecast":"sunny"}', "schema:additionalProperties"),
        ("enum", ACCEPTED_JSON.replace('"C"', '"K"'), "schema:enum"),
        ("wrong unit", ACCEPTED_JSON.replace('"C"', '"F"'), "business:request_mismatch"),
        ("duplicate name", ACCEPTED_JSON[:-1] + ',"city":"Shanghai"}', "invalid_json"),
        ("NaN", ACCEPTED_JSON.replace("21", "NaN"), "invalid_json"),
        ("temperature fact outside request check", ACCEPTED_JSON.replace("21", "27"), "accepted"),
    ]:
        check(f"local {label}", validate_weather(payload), expected)

    nullable = {"type": "object", "properties": {"note": {"type": ["string", "null"]}},
                "required": ["note"], "additionalProperties": False}
    note_validator = Draft202012Validator(nullable)
    check("required nullable accepts explicit null", note_validator.is_valid({"note": None}), True)
    check("required nullable rejects omission", note_validator.is_valid({}), False)

    email = {"type": "string", "format": "email"}
    check("format without checker", Draft202012Validator(email).is_valid("not-an-email"), True)
    check("format with checker", Draft202012Validator(
        email, format_checker=FormatChecker()).is_valid("not-an-email"), False)
    supported = (0, 2)
    logits = (2.0, 1.0, 0.0)
    mass = sum(exp(logits[index]) for index in supported)
    constrained = [exp(score) / mass if index in supported else 0.0
                   for index, score in enumerate(logits)]
    assert isclose(sum(constrained), 1.0)
    check("masked sampling example", [round(p, 6) for p in constrained], [0.880797, 0.0, 0.119203])


def check_api_replay():
    for api, reply, consume in [
        ("chat", chat_reply, consume_chat), ("responses", responses_reply, consume_responses),
    ]:
        for label, mode, payload, expected in [
            ("JSON mode wrong type", "json", WRONG_TYPE, "schema:type"),
            ("JSON mode success", "json", ACCEPTED_JSON, "accepted"),
            ("strict business mismatch", "strict", WRONG_CITY, "business:request_mismatch"),
            ("strict success", "strict", ACCEPTED_JSON, "accepted"),
        ]:
            check(f"{api} {label}", consume(mock_call(api, mode, reply(payload))), expected)
        refused = reply(None, refusal="Fixture refusal")
        check(f"{api} refusal", consume(mock_call(api, "strict", refused)), "refusal")
        typed = mock_call(api, "typed", reply(ACCEPTED_JSON))
        parsed = typed.choices[0].message.parsed if api == "chat" else typed.output_parsed
        check(f"{api} typed success", parsed.model_dump(), json.loads(ACCEPTED_JSON))
        typed = mock_call(api, "typed", refused)
        parsed = typed.choices[0].message.parsed if api == "chat" else typed.output_parsed
        check(f"{api} typed refusal has no parsed result", parsed, None)

    for reason, expected_error in [("length", LengthFinishReasonError),
                                   ("content_filter", ContentFilterFinishReasonError)]:
        chat = chat_reply(PARTIAL, reason)
        check(f"chat {reason}", consume_chat(mock_call("chat", "strict", chat)), f"finish:{reason}")
        check_raises(f"chat typed {reason}", expected_error, lambda: mock_call("chat", "typed", chat))

    for reason in ("max_output_tokens", "content_filter"):
        response = responses_reply(PARTIAL, "incomplete", reason)
        check(f"responses {reason}", consume_responses(mock_call("responses", "strict", response)),
              f"incomplete:{reason}")
    check_raises("responses typed incomplete text", TypedParseError,
                 lambda: mock_call("responses", "typed", responses_reply(PARTIAL, "incomplete", "max_output_tokens")))
    truncated_after_text = responses_reply(ACCEPTED_JSON, "incomplete", "max_output_tokens")
    typed = mock_call("responses", "typed", truncated_after_text)
    check("responses typed incomplete with parseable text", typed.output_parsed.city, "Beijing")
    check("incomplete envelope remains authoritative for consumer", consume_responses(typed),
          "incomplete:max_output_tokens")


def check_schema_subset():
    wider_schema = deepcopy(SCHEMA)
    wider_schema["properties"]["temperature"] = {"allOf": [{"type": "number"}, {"minimum": -273.15}]}
    Draft202012Validator.check_schema(wider_schema)
    check("allOf legal and valid locally", Draft202012Validator(wider_schema).is_valid(json.loads(ACCEPTED_JSON)), True)
    error_body = {"error": {"message": "Fixture rejected unsupported allOf", "type": "invalid_request_error",
                            "code": "invalid_json_schema"}}
    for api in ("chat", "responses"):
        error = check_raises(f"{api} unsupported schema simulated HTTP 400", BadRequestError,
                             lambda: mock_call(api, "strict", error_body, schema=wider_schema, status_code=400))
        check(f"{api} mock error status", error.status_code, 400)


if __name__ == "__main__":
    print(f"Python {platform.python_version()} | " + " | ".join(
        f"{package} {version(package)}" for package in ("openai", "httpx", "pydantic", "jsonschema")))
    check_local_validation()
    check_api_replay()
    check_schema_subset()
