"""Run with Python 3.12 and openai 1.109.1. All model traffic stays in MockTransport."""

import asyncio
from dataclasses import dataclass
from importlib.metadata import version
import json
import sys

import httpx
from openai import OpenAI


MODEL = "gpt-4o-2024-08-06"  # Historical fixture label only.
FUNCTION = "get_weather"
TEMPERATURES = {"Beijing": 21, "Shanghai": 26}
PAIR_PROMPT = "Compare the mock observations for Beijing and Shanghai in degrees Celsius."
PAIR_FINAL = "Beijing: 21 C. Shanghai: 26 C."
ONE_PROMPT = "Read the mock Beijing observation in degrees Celsius."
ONE_FINAL = "Beijing: 21 C."
DIRECT_PROMPT = "What can you report without requesting a weather observation?"
DIRECT_FINAL = "I have no mock observation yet."
DECLARATION = {
    "name": FUNCTION,
    "description": "Read a fixed teaching observation in Celsius.",
    "parameters": {
        "type": "object",
        "properties": {"city": {"type": "string", "enum": list(TEMPERATURES)}},
        "required": ["city"],
        "additionalProperties": False,
    },
    "strict": True,
}
CHAT_TOOL = {"type": "function", "function": DECLARATION}
RESPONSES_TOOL = {"type": "function", **DECLARATION}


@dataclass(frozen=True)
class Call:
    call_id: str
    name: str
    arguments: str


class ProtocolError(ValueError):
    """The non-streaming fixture violates this toy application's contract."""


def weather_arguments(call):
    if call.name != FUNCTION or not call.call_id:
        raise ProtocolError("invalid function name or call ID")
    args = json.loads(call.arguments)
    if (not isinstance(args, dict) or set(args) != {"city"}
            or not isinstance(args["city"], str) or args["city"] not in TEMPERATURES):
        raise ProtocolError("unexpected weather arguments")
    return args["city"]


async def execute_weather_batch(calls, starts, completions):
    # These Events force an interleaved completion order without wall-clock sleeps.
    first_started = asyncio.Event()
    second_finished = asyncio.Event()
    if len({call.call_id for call in calls}) != len(calls):
        raise ProtocolError("duplicate proposal ID")
    if len(calls) not in (1, 2):
        raise ProtocolError("toy batch size")
    inputs = [(call, weather_arguments(call)) for call in calls]

    async def get_weather(index, call, city):
        if index == 1:
            await first_started.wait()
        starts.append(city)
        if index == 0:
            first_started.set()
            if len(inputs) == 2:
                await second_finished.wait()
        observation = {"city": city, "temperature": TEMPERATURES[city], "unit": "C"}
        completions.append(city)
        if index == 1:
            second_finished.set()
        return call.call_id, observation

    by_id = {}
    jobs = [get_weather(i, call, city) for i, (call, city) in enumerate(inputs)]
    for job in asyncio.as_completed(jobs):
        call_id, observation = await job
        by_id[call_id] = observation
    return by_id


def chat_turn(result):
    if len(result.choices) != 1:
        raise ProtocolError("expected one Chat choice")
    choice = result.choices[0]
    message = choice.message
    if message.refusal is not None:
        raise ProtocolError("refusal")
    if message.role != "assistant" or message.function_call is not None:
        raise ProtocolError("unexpected Chat message")
    tools = message.tool_calls or []
    if choice.finish_reason == "tool_calls" and tools:
        if any(tool.type != "function" for tool in tools):
            raise ProtocolError("expected Chat function calls")
        calls = [Call(tool.id, tool.function.name, tool.function.arguments) for tool in tools]
        history = message.model_dump(exclude_none=True)
        return calls, [history], ""
    if choice.finish_reason == "stop" and not tools and (message.content or "").strip():
        return [], [], message.content
    raise ProtocolError(f"invalid Chat turn: {choice.finish_reason}")


def responses_turn(result):
    if result.status != "completed":
        raise ProtocolError(f"invalid Responses turn: {result.status}")
    calls, texts = [], []
    for item in result.output:
        if item.type == "function_call":
            if item.status not in (None, "completed"):
                raise ProtocolError(f"incomplete function call: {item.status}")
            calls.append(Call(item.call_id, item.name, item.arguments))
        elif item.type == "message" and item.role == "assistant" and item.status == "completed":
            for part in item.content:
                if part.type == "refusal":
                    raise ProtocolError("refusal")
                if part.type != "output_text":
                    raise ProtocolError("unexpected Responses content")
                texts.append(part.text)
        else:
            raise ProtocolError("unexpected Responses output item in this fixture")
    if calls:
        return calls, [item.model_dump(exclude_none=True) for item in result.output], ""
    final = "".join(texts)
    if not final.strip():
        raise ProtocolError("missing final text")
    return [], [], final


def make_result_item(endpoint, call_id, observation):
    payload = json.dumps(observation, ensure_ascii=False, separators=(",", ":"))
    if endpoint == "chat":
        return {"role": "tool", "tool_call_id": call_id, "content": payload}
    return {"type": "function_call_output", "call_id": call_id, "output": payload}


@dataclass(frozen=True)
class Outcome:
    status: str
    text: str
    tool_batches: int


def run_weather(client, endpoint, prompt, starts, completions, max_tool_batches=1):
    if max_tool_batches < 0:
        raise ValueError("max_tool_batches must be nonnegative")
    history = [{"role": "user", "content": prompt}]
    batches = 0
    # The extra request can consume the last batch and produce final text.
    for _ in range(max_tool_batches + 1):
        if endpoint == "chat":
            result = client.chat.completions.create(
                model=MODEL, messages=history, tools=[CHAT_TOOL],
                parallel_tool_calls=True, tool_choice="auto",
            )
            calls, prior_output, text = chat_turn(result)
        else:
            result = client.responses.create(
                model=MODEL, input=history, tools=[RESPONSES_TOOL], store=False,
                parallel_tool_calls=True, tool_choice="auto",
            )
            calls, prior_output, text = responses_turn(result)
        if not calls:
            return Outcome("final", text, batches)
        if batches == max_tool_batches:
            return Outcome("tool_budget", "", batches)
        by_id = asyncio.run(execute_weather_batch(calls, starts, completions))
        history.extend(prior_output)
        history.extend(make_result_item(endpoint, call.call_id, by_id[call.call_id]) for call in calls)
        batches += 1


def tool_proposals(endpoint, turn, cities):
    result = []
    for index, city in enumerate(cities):
        call_id = f"call_{endpoint}_{turn}_{index}"
        args = json.dumps({"city": city}, separators=(",", ":"))
        if endpoint == "chat":
            result.append({
                "id": call_id, "type": "function",
                "function": {"name": FUNCTION, "arguments": args},
            })
        else:
            result.append({
                "id": f"fc_fixture_{turn}_{index}", "call_id": call_id,
                "type": "function_call", "name": FUNCTION,
                "arguments": args, "status": "completed",
            })
    return result


def fixture(endpoint, turn, case):
    wants_tools = (case in {"one", "pair", "repeat", "truncated", "duplicate", "refusal"}
                   and (turn == 0 or case == "repeat"))
    cities = ["Beijing"] if case == "one" else ["Beijing", "Shanghai"]
    proposals = tool_proposals(endpoint, turn, cities) if wants_tools else []
    final_text = {"direct": DIRECT_FINAL, "one": ONE_FINAL}.get(case, PAIR_FINAL)
    if case == "duplicate":
        id_field = "id" if endpoint == "chat" else "call_id"
        proposals[1][id_field] = proposals[0][id_field]
    if endpoint == "chat":
        message = {"role": "assistant", "content": None if proposals else final_text}
        if proposals:
            message["tool_calls"] = proposals
        if case == "refusal":
            message["refusal"] = "Fixture refusal."
        reason = "length" if case == "truncated" else ("tool_calls" if proposals else "stop")
        return {
            "id": f"chatcmpl_fixture_{turn}", "object": "chat.completion",
            "created": 0, "model": MODEL,
            "choices": [{"index": 0, "finish_reason": reason, "message": message}],
        }
    output = list(proposals)
    if not proposals or case == "refusal":
        part = {"type": "refusal", "refusal": "Fixture refusal."} if case == "refusal" else {
            "type": "output_text", "text": final_text, "annotations": [],
        }
        output.append({
            "type": "message", "id": f"msg_fixture_{turn}",
            "role": "assistant", "status": "completed", "content": [part],
        })
    return {
        "id": f"resp_fixture_{turn}", "object": "response",
        "created_at": 0, "model": MODEL, "instructions": None,
        "status": "incomplete" if case == "truncated" else "completed",
        "incomplete_details": {"reason": "max_output_tokens"} if case == "truncated" else None,
        "output": output, "parallel_tool_calls": True, "tool_choice": "auto",
        "tools": [RESPONSES_TOOL],
    }


def mock_client(endpoint, case, requests, wire_orders):
    def handle(request):
        path = "/v1/chat/completions" if endpoint == "chat" else "/v1/responses"
        assert request.method == "POST" and request.url.path == path
        body = json.loads(request.content)
        assert body["model"] == MODEL and body["parallel_tool_calls"] is True
        assert body["tool_choice"] == "auto"
        assert body["tools"] == ([CHAT_TOOL] if endpoint == "chat" else [RESPONSES_TOOL])
        history = body["messages" if endpoint == "chat" else "input"]
        expected_prompt = {"direct": DIRECT_PROMPT, "one": ONE_PROMPT}.get(case, PAIR_PROMPT)
        assert history[0] == {"role": "user", "content": expected_prompt}
        turn = len(requests)
        if endpoint == "responses":
            assert body["store"] is False and "previous_response_id" not in body
        start = 1
        for previous_turn in range(turn):
            previous = fixture(endpoint, previous_turn, case)
            cities = []
            if endpoint == "chat":
                message = previous["choices"][0]["message"]
                calls = message["tool_calls"]
                assert history[start] == {"role": "assistant", "tool_calls": calls}
                start += 1
                id_field, payload_field = "tool_call_id", "content"
                expected = {call["id"]: json.loads(call["function"]["arguments"])["city"] for call in calls}
            else:
                calls = previous["output"]
                assert history[start:start + len(calls)] == calls
                start += len(calls)
                id_field, payload_field = "call_id", "output"
                expected = {call["call_id"]: json.loads(call["arguments"])["city"] for call in calls}
            batch = history[start:start + len(calls)]
            assert [item[id_field] for item in batch] == list(expected)
            for item in batch:
                assert isinstance(item[payload_field], str)
                observation = json.loads(item[payload_field])
                city = expected[item[id_field]]
                assert observation == {"city": city, "temperature": TEMPERATURES[city], "unit": "C"}
                assert item == make_result_item(endpoint, item[id_field], observation)
                cities.append(city)
            wire_orders.append(cities)
            start += len(calls)
        assert len(history) == start
        requests.append(body)
        return httpx.Response(200, json=fixture(endpoint, turn, case))

    return OpenAI(
        api_key="mock-key",
        base_url="https://weather-tool-fixture.invalid/v1",
        max_retries=0,
        http_client=httpx.Client(transport=httpx.MockTransport(handle), trust_env=False),
    )


def verify(endpoint, case, budget, expected, request_count, starts, completions, wire):
    observed_starts, observed_completions, observed_wire, requests = [], [], [], []
    prompt = {"direct": DIRECT_PROMPT, "one": ONE_PROMPT}.get(case, PAIR_PROMPT)
    with mock_client(endpoint, case, requests, observed_wire) as client:
        if isinstance(expected, str):
            try:
                run_weather(client, endpoint, prompt, observed_starts, observed_completions, budget)
            except ProtocolError as exc:
                assert str(exc) == expected, exc
            else:
                raise AssertionError("expected a ProtocolError")
        else:
            assert run_weather(client, endpoint, prompt, observed_starts, observed_completions, budget) == expected
    assert len(requests) == request_count
    assert observed_starts == starts and observed_completions == completions
    assert observed_wire == wire
    print(f"PASS {endpoint}/{case}/{budget}: requests={len(requests)}, "
          f"starts={observed_starts}, finishes={observed_completions}, wire={observed_wire}, {expected}")


def main():
    assert version("openai") == "1.109.1"
    print(f"Python {sys.version.split()[0]} | openai {version('openai')} | "
          f"httpx {version('httpx')} | pydantic {version('pydantic')}")
    pair = ["Beijing", "Shanghai"]
    reverse = list(reversed(pair))
    for endpoint in ("chat", "responses"):
        verify(endpoint, "direct", 0, Outcome("final", DIRECT_FINAL, 0), 1, [], [], [])
        verify(endpoint, "one", 1, Outcome("final", ONE_FINAL, 1), 2, ["Beijing"], ["Beijing"], [["Beijing"]])
        verify(endpoint, "pair", 1, Outcome("final", PAIR_FINAL, 1), 2, pair, reverse, [pair])
        verify(endpoint, "repeat", 1, Outcome("tool_budget", "", 1), 2, pair, reverse, [pair])
        verify(endpoint, "pair", 0, Outcome("tool_budget", "", 0), 1, [], [], [])
        verify(endpoint, "duplicate", 1, "duplicate proposal ID", 1, [], [], [])
        verify(endpoint, "refusal", 1, "refusal", 1, [], [], [])
        error = "invalid Chat turn: length" if endpoint == "chat" else "invalid Responses turn: incomplete"
        verify(endpoint, "truncated", 1, error, 1, [], [], [])
    print("16/16 local scenarios passed. Online endpoints and real weather: not_run.")


if __name__ == "__main__":
    main()
