"""Offline contract checks using the real OpenAI Python SDK and a mock transport."""

import json
import sys
from importlib.metadata import version

import httpx
from openai import APIConnectionError, APITimeoutError, BadRequestError, InternalServerError, OpenAI, RateLimitError

MODEL = "gpt-4o-2024-08-06"
INSTRUCTIONS = "Use the supplied fictional weather observation only."
QUESTION = "What is the temperature in Beijing? Fictional weather observation: 21 °C."
TEXT = "The fictional observation for Beijing is 21 °C."
CHAT_PATH = "/v1/chat/completions"
RESPONSES_PATH = "/v1/responses"
HEADERS = {"x-request-id": "req_mock_weather"}
WEATHER_TOOL = {
    "name": "get_weather", "description": "Read a fictional city temperature.", "strict": True,
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
                   "required": ["city"], "additionalProperties": False},
}


def chat_body(case):
    message = {"role": "assistant", "content": TEXT}
    finish_reason = "stop"
    completion_tokens = 10
    if case == "limit":
        message["content"] = "The fictional"
        finish_reason = "length"
        completion_tokens = 32
    elif case == "tool":
        message = {"role": "assistant", "content": None, "tool_calls": [{
            "id": "call_chat_beijing", "type": "function",
            "function": {"name": "get_weather", "arguments": '{"city":"Beijing"}'},
        }]}
        finish_reason = "tool_calls"
    return {
        "id": "chatcmpl_mock_weather", "object": "chat.completion", "created": 1760000000,
        "model": MODEL, "choices": [{"index": 0, "message": message, "finish_reason": finish_reason}],
        "usage": {"prompt_tokens": 24, "completion_tokens": completion_tokens, "total_tokens": 24 + completion_tokens,
                  "prompt_tokens_details": {"cached_tokens": 0},
                  "completion_tokens_details": {"reasoning_tokens": 0}},
    }


def responses_body(case):
    text = {"type": "output_text", "text": TEXT, "annotations": []}
    output = [{"id": "msg_mock_weather", "type": "message", "role": "assistant",
               "status": "completed", "content": [text]}]
    body = {
        "id": "resp_mock_weather", "object": "response", "created_at": 1760000000,
        "model": MODEL, "status": "completed", "output": output, "error": None,
        "incomplete_details": None, "parallel_tool_calls": False,
        "tools": [], "tool_choice": "auto",
        "usage": {"input_tokens": 24, "output_tokens": 10, "total_tokens": 34,
                  "input_tokens_details": {"cached_tokens": 0},
                  "output_tokens_details": {"reasoning_tokens": 0}},
    }
    if case == "limit":
        body.update(status="incomplete", incomplete_details={"reason": "max_output_tokens"})
        output[0]["status"] = "incomplete"
        text["text"] = "The fictional"
        body["usage"].update(output_tokens=32, total_tokens=56)
    elif case == "tool":
        body["output"] = [{"type": "function_call", "id": "fc_mock_item", "call_id": "call_res_beijing",
                           "name": "get_weather", "arguments": '{"city":"Beijing"}', "status": "completed"}]
    elif case == "failed":
        body.update(status="failed", error={"code": "server_error", "message": "Mock generation failed"},
                    output=[], usage=None)
    return body


def request_chat(client, tool=False):
    options = {"tools": [{"type": "function", "function": WEATHER_TOOL}]} if tool else {}
    return client.chat.completions.create(
        model=MODEL, messages=[{"role": "developer", "content": INSTRUCTIONS},
                               {"role": "user", "content": QUESTION}],
        temperature=0.2, max_completion_tokens=32, **options,
    )


def request_responses(client, tool=False):
    options = {"tools": [{"type": "function", **WEATHER_TOOL}]} if tool else {}
    return client.responses.create(model=MODEL, instructions=INSTRUCTIONS, input=QUESTION,
                                   temperature=0.2, max_output_tokens=32, store=False, **options)


def open_mock(expected_path, cases, max_retries=0):
    requests = []

    def handle(request):
        assert request.url.host == "offline.invalid"
        assert request.url.path == expected_path and request.method == "POST"
        data = json.loads(request.content)
        case = cases[len(requests)]
        common = {"model": MODEL, "temperature": 0.2}
        if expected_path == CHAT_PATH:
            expected = {**common, "messages": [{"role": "developer", "content": INSTRUCTIONS},
                                               {"role": "user", "content": QUESTION}],
                        "max_completion_tokens": 32}
            if case == "tool":
                expected["tools"] = [{"type": "function", "function": WEATHER_TOOL}]
        else:
            expected = {**common, "instructions": INSTRUCTIONS, "input": QUESTION,
                        "max_output_tokens": 32, "store": False}
            if case == "tool":
                expected["tools"] = [{"type": "function", **WEATHER_TOOL}]
        assert data == expected
        assert request.extensions["timeout"] == {"connect": 0.5, "read": 2.0, "write": 2.0, "pool": 2.0}
        requests.append(data)
        if case == "timeout":
            raise httpx.ReadTimeout("simulated read timeout", request=request)
        if case == "connection":
            raise httpx.ConnectError("simulated connection failure", request=request)
        if isinstance(case, int):
            headers = {**HEADERS, "retry-after-ms": "1"} if case == 429 else HEADERS
            return httpx.Response(case, headers=headers, json={"error": {
                "message": "Mock HTTP error", "type": "mock_error", "code": f"mock_{case}",
            }})
        body = chat_body(case) if expected_path == CHAT_PATH else responses_body(case)
        return httpx.Response(200, headers=HEADERS, json=body)

    client = OpenAI(api_key="mock-key", base_url="https://offline.invalid/v1",
                    http_client=httpx.Client(transport=httpx.MockTransport(handle)),
                    timeout=httpx.Timeout(2.0, connect=0.5), max_retries=max_retries)
    return client, requests


def read(path, send, case):
    client, requests = open_mock(path, [case])
    with client:
        result = send(client, tool=(case == "tool"))
    assert len(requests) == 1 and result._request_id == HEADERS["x-request-id"]
    return result


def check_success(path, send):
    result = read(path, send, "ok")
    if path == CHAT_PATH:
        assert result.choices[0].finish_reason == "stop"
        assert result.choices[0].message.content == TEXT
        assert result.usage.prompt_tokens + result.usage.completion_tokens == result.usage.total_tokens == 34
    else:
        assert result.status == "completed" and result.output_text == TEXT
        assert result.usage.input_tokens + result.usage.output_tokens == result.usage.total_tokens == 34
    print(f"PASS {path}: JSON request, text and usage, request ID")


def check_error(path, send, case, error_type):
    client, requests = open_mock(path, [case])
    with client:
        try:
            send(client)
        except error_type as exc:
            assert type(exc) is error_type
            if isinstance(case, int):
                assert exc.status_code == case and exc.code == f"mock_{case}"
                assert exc.request_id == HEADERS["x-request-id"]
        else:
            raise AssertionError(f"Missing expected {error_type.__name__}")
    assert len(requests) == 1
    print(f"PASS {path}: {case} -> {error_type.__name__}; attempts=1")


def main():
    assert version("openai") == "1.109.1" and version("httpx") == "0.28.1"
    print(f"Python {sys.version.split()[0]}, openai {version('openai')}, httpx {version('httpx')}, pydantic {version('pydantic')}")
    for path, send in ((CHAT_PATH, request_chat), (RESPONSES_PATH, request_responses)):
        check_success(path, send)
        for case, error in ((400, BadRequestError), (429, RateLimitError), (500, InternalServerError),
                            ("timeout", APITimeoutError), ("connection", APIConnectionError)):
            check_error(path, send, case, error)
    chat = read(CHAT_PATH, request_chat, "limit")
    response = read(RESPONSES_PATH, request_responses, "limit")
    assert chat.choices[0].finish_reason == "length" and chat.choices[0].message.content == "The fictional"
    assert response.status == "incomplete" and response.incomplete_details.reason == "max_output_tokens"
    assert response.output_text == "The fictional"
    assert chat.usage.completion_tokens == response.usage.output_tokens == 32
    print("PASS output limit: Chat length, Responses incomplete/max_output_tokens, partial text")

    chat = read(CHAT_PATH, request_chat, "tool")
    response = read(RESPONSES_PATH, request_responses, "tool")
    assert chat.choices[0].finish_reason == "tool_calls" and chat.choices[0].message.content is None
    assert chat.choices[0].message.tool_calls[0].id == "call_chat_beijing"
    assert response.status == "completed" and response.output_text == ""
    assert response.output[0].type == "function_call"
    assert response.output[0].id == "fc_mock_item" and response.output[0].call_id == "call_res_beijing"
    print("PASS output dispatch: tool-only Chat/Responses, Responses item id distinct from call_id")

    response = read(RESPONSES_PATH, request_responses, "failed")
    assert response.status == "failed" and response.error.code == "server_error" and response.usage is None
    print("PASS HTTP 200 with Responses status=failed and no usage")

    client, requests = open_mock(RESPONSES_PATH, [429, "ok"], max_retries=1)
    with client:
        assert request_responses(client).status == "completed"
    assert len(requests) == 2 and requests[0] == requests[1]
    print("PASS configured retry: 429 -> 200; attempts=2; same request body")
    print("16 checks passed. Transport=MockTransport. OpenAI cloud and weather service: not_run.")


if __name__ == "__main__":
    main()
