#!/usr/bin/env python3
"""Offline, synthetic unified-API example; not a production gateway.

Python 3.11; python -m pip install openai==3.49.0 anthropic==2.8.0 httpx2==2.16.0
No API keys, network calls, real weather or live model output.
One ORIGINAL_CONTENT dictionary per conversation; do not share across users.
Only the text/function-tool/strict-JSON examples in the article are supported.
"""
import json
from copy import deepcopy

# Single-conversation demo state. A gateway needs isolated, bounded storage.
ORIGINAL_CONTENT = {}


def to_anthropic(req):
    system, messages = [], []
    for m in req["messages"]:
        if m["role"] in ("system", "developer"):
            system.append(m["content"])
        elif m["role"] == "tool":
            block = {"type": "tool_result", "tool_use_id": m["tool_call_id"], "content": m["content"]}
            messages.append({"role": "user", "content": [block]})
        elif m.get("tool_calls") and m["tool_calls"][0]["id"] in ORIGINAL_CONTENT:
            messages.append({"role": "assistant", "content": deepcopy(ORIGINAL_CONTENT[m["tool_calls"][0]["id"]])})
        elif m.get("tool_calls"):
            blocks = [{"type": "text", "text": m["content"]}] if m.get("content") else []
            for tc in m["tool_calls"]:
                blocks.append({"type": "tool_use", "id": tc["id"], "name": tc["function"]["name"],
                               "input": json.loads(tc["function"]["arguments"])})
            messages.append({"role": "assistant", "content": blocks})
        else:
            messages.append({"role": m["role"], "content": m["content"]})
    out = {"model": req["model"], "messages": messages,
           "max_tokens": req.get("max_completion_tokens") or req.get("max_tokens") or 4096}
    if system:
        out["system"] = "\n\n".join(system)
    if req.get("tools"):
        out["tools"] = []
        for tool in req["tools"]:
            f = tool["function"]
            native = {"name": f["name"], "description": f.get("description", ""),
                      "input_schema": deepcopy(f["parameters"])}
            # Preserve explicit False as well as True; omit only when absent.
            if "strict" in f:
                native["strict"] = f["strict"]
            out["tools"].append(native)
    choice = req.get("tool_choice")
    if choice:
        if isinstance(choice, dict):
            out["tool_choice"] = {"type": "tool", "name": choice["function"]["name"]}
        else:
            out["tool_choice"] = {"type": {"auto": "auto", "none": "none", "required": "any"}[choice]}
    rf = req.get("response_format")
    if rf and rf["type"] == "json_schema":
        out["output_config"] = {"format": {"type": "json_schema", "schema": deepcopy(rf["json_schema"]["schema"])}}
    return out


def from_anthropic(reply):
    """Map supported non-streaming replies and save the unmodified tool turn."""
    finish = {"end_turn": "stop", "stop_sequence": "stop", "max_tokens": "length",
              "tool_use": "tool_calls"}
    if reply["stop_reason"] not in finish:
        raise ValueError("This demo does not map stop reason: " + str(reply["stop_reason"]))
    content = reply["content"]
    calls = []
    for block in content:
        if block["type"] == "tool_use":
            ORIGINAL_CONTENT[block["id"]] = deepcopy(content)
            calls.append({"id": block["id"], "type": "function", "function": {
                "name": block["name"], "arguments": json.dumps(block["input"])}})
    text = "".join(b["text"] for b in content if b["type"] == "text")
    message = {"role": "assistant", "content": text or None}
    if calls:
        message["tool_calls"] = calls
    # The fixture has uncached usage only; this is not a billing adapter.
    prompt, completion = reply["usage"]["input_tokens"], reply["usage"]["output_tokens"]
    return {"id": reply["id"], "object": "chat.completion", "created": 0,
            "model": reply["model"],
            "choices": [{"index": 0, "message": message, "finish_reason": finish[reply["stop_reason"]]}],
            "usage": {"prompt_tokens": prompt, "completion_tokens": completion,
                      "total_tokens": prompt + completion}}


# New synthetic fixtures reproduce the article's illustrative payloads. They are
# not captured provider responses. The signature is intentionally nonfunctional.
MODEL = "claude-sonnet-5-5"
WEATHER = {
    "model": MODEL,
    "messages": [
        {"role": "system", "content": "You answer weather questions."},
        {"role": "user", "content": "What's the weather like in San Francisco right now, and what time is it there?"}],
    "tools": [{"type": "function", "function": {
        "name": "get_weather", "description": "Get the current weather in a given location",
        "parameters": {"type": "object", "properties": {
            "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"],
                     "description": "The unit of temperature, either 'celsius' or 'fahrenheit'"}},
            "required": ["location"]}}}],
    "tool_choice": "auto"}
TOOL_REPLY = {
    "id": "msg_01234", "type": "message", "role": "assistant", "model": MODEL,
    "content": [
        {"type": "thinking", "thinking": "", "signature": "EosnCkYICxIMMb3LzNrMu..."},
        {"type": "text", "text": "I'll help you check the current weather and time in San Francisco."},
        {"type": "tool_use", "id": "toolu_01A09q90qw90lq917835lq9", "name": "get_weather",
         "input": {"location": "San Francisco, CA"}}],
    "stop_reason": "tool_use", "stop_sequence": None, "stop_details": None,
    "usage": {"input_tokens": 100, "output_tokens": 50}}
CONTACT = {
    "model": MODEL,
    "messages": [{"role": "user", "content": "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."}],
    "response_format": {"type": "json_schema", "json_schema": {
        "name": "contact", "strict": True,
        "schema": {"type": "object", "properties": {
            "name": {"type": "string"}, "email": {"type": "string"},
            "plan_interest": {"type": "string"}, "demo_requested": {"type": "boolean"}},
            "required": ["name", "email", "plan_interest", "demo_requested"],
            "additionalProperties": False}}}}
CONTACT_REPLY = deepcopy(TOOL_REPLY)
CONTACT_REPLY.update(content=[{"type": "text", "text": json.dumps({
    "name": "John Smith", "email": "john@example.com", "plan_interest": "Enterprise",
    "demo_requested": True}, indent=2)}], stop_reason="end_turn")
TOOL_RESULT = {"role": "tool", "tool_call_id": "toolu_01A09q90qw90lq917835lq9",
               "content": "SYNTHETIC tool output: 15 degrees celsius, sunny"}
OVERLOADED = {"type": "error", "error": {
    "message": "The API is temporarily overloaded.", "type": "overloaded_error"}}


def self_test():
    """Local regression checks: no provider/schema-enforcement claim."""
    ORIGINAL_CONTENT.clear()
    for flag in (True, False, None):
        request = deepcopy(WEATHER)
        function = request["tools"][0]["function"]
        # A closed, fully required schema for the strict-input check.
        function["parameters"]["additionalProperties"] = False
        function["parameters"]["required"] = ["location", "unit"]
        if flag is not None:
            function["strict"] = flag
        translated = to_anthropic(request)["tools"][0]
        assert ("strict" in translated) == (flag is not None)
        if flag is not None:
            assert translated["strict"] is flag
        assert translated["input_schema"] == function["parameters"]
    reply = deepcopy(TOOL_REPLY)
    # Redacted content must survive too, including its position in the turn.
    reply["content"].insert(1, {"type": "redacted_thinking", "data": "synthetic-opaque-data"})
    completion = from_anthropic(reply)
    follow = deepcopy(WEATHER)
    follow["messages"] += [completion["choices"][0]["message"], deepcopy(TOOL_RESULT)]
    original = deepcopy(reply["content"])
    reply["content"][0]["signature"] = "mutated"
    translated = to_anthropic(follow)
    assert translated["messages"][1]["content"] == original
    translated["messages"][1]["content"][0]["signature"] = "mutated again"
    assert to_anthropic(follow)["messages"][1]["content"] == original
    assert completion["choices"][0]["finish_reason"] == "tool_calls"
    assert completion["usage"] == {"prompt_tokens": 100, "completion_tokens": 50, "total_tokens": 150}
    for reason, expected in (("end_turn", "stop"), ("stop_sequence", "stop"), ("max_tokens", "length")):
        response = deepcopy(CONTACT_REPLY)
        response["stop_reason"] = reason
        assert from_anthropic(response)["choices"][0]["finish_reason"] == expected
    response["stop_reason"] = "pause_turn"
    try:
        from_anthropic(response)
    except ValueError:
        pass
    else:
        raise AssertionError("Unsupported stop reason silently mapped")
    ORIGINAL_CONTENT.clear()


def main():
    # These pinned SDKs use httpx2, not httpx 0.x, for their custom client.
    import httpx2
    from anthropic import Anthropic, APIStatusError
    from openai import OpenAI

    self_test()
    seen = []
    overload = False

    def provider(request):
        assert request.url.host == "anthropic.invalid"
        assert request.url.path == "/v1/messages"
        native = json.loads(request.content)
        seen.append(native)
        if overload:
            return httpx2.Response(529, json=OVERLOADED)
        if "output_config" in native:
            fixture = CONTACT_REPLY
        elif native["messages"][-1]["role"] == "user" and isinstance(native["messages"][-1]["content"], list):
            assert native["messages"][-2]["content"] == TOOL_REPLY["content"]
            fixture = deepcopy(CONTACT_REPLY)
            fixture["content"] = [{"type": "text", "text": "SYNTHETIC final weather answer."}]
        else:
            fixture = TOOL_REPLY
        return httpx2.Response(200, json=fixture)

    def show(label, value):
        print(label)
        print(json.dumps(value, indent=2))

    with Anthropic(api_key="offline-demo", base_url="https://anthropic.invalid",
                   max_retries=0, http_client=httpx2.Client(transport=httpx2.MockTransport(provider))) as native_client:
        def send(req):
            raw = native_client.messages.with_raw_response.create(**to_anthropic(req))
            payload = raw.http_response.json()
            assert raw.parse().model_dump(mode="json", exclude_unset=True) == payload
            # Preserve wire field order for the article's printed payloads.
            return payload

        show("--- 1a OpenAI-shape request from the client", WEATHER)
        show("--- 1b same request in Anthropic Messages shape", to_anthropic(WEATHER))
        reply = send(WEATHER)
        assert seen[-1] == to_anthropic(WEATHER)
        show("--- 1c Anthropic response fixture", reply)
        completion = from_anthropic(reply)
        show("--- 1d normalised to OpenAI chat completion shape", completion)
        follow = deepcopy(WEATHER)
        follow["messages"] += [completion["choices"][0]["message"], deepcopy(TOOL_RESULT)]
        native_follow = to_anthropic(follow)
        show("--- 2 follow-up request in Anthropic Messages shape (tool_use and tool_result blocks)", native_follow)
        send(follow)
        assert seen[-1] == native_follow
        kept = [b["type"] for b in native_follow["messages"][1]["content"]]
        saved = deepcopy(ORIGINAL_CONTENT)
        ORIGINAL_CONTENT.clear()
        lost = [b["type"] for b in to_anthropic(follow)["messages"][1]["content"]]
        ORIGINAL_CONTENT.update(saved)
        print("2b assistant turn sent back unchanged, block types:", kept)
        print("2c rebuilt from tool_calls alone, block types:", lost, "(thinking block lost)")
        show("--- 3a OpenAI-shape request with response_format json_schema", CONTACT)
        show("--- 3b same request in Anthropic Messages shape (output_config.format)", to_anthropic(CONTACT))
        show("--- 3c normalised to OpenAI chat completion shape", from_anthropic(send(CONTACT)))

        def gateway(request):
            assert request.url.host == "gateway.invalid"
            assert request.url.path == "/v1/chat/completions"
            return httpx2.Response(200, json=from_anthropic(send(json.loads(request.content))))

        with OpenAI(api_key="offline-demo", base_url="https://gateway.invalid/v1", max_retries=0,
                    http_client=httpx2.Client(transport=httpx2.MockTransport(gateway))) as client:
            # Exercise strict flags through both SDK serializers, too.
            for flag in (True, False):
                strict_req = deepcopy(WEATHER)
                function = strict_req["tools"][0]["function"]
                function["parameters"] = {"type": "object", "properties": {
                    "location": {"type": "string"}}, "required": ["location"],
                    "additionalProperties": False}
                function["strict"] = flag
                client.chat.completions.create(**strict_req)
                assert seen[-1]["tools"][0]["strict"] is flag
            result = client.chat.completions.create(**WEATHER)
            print("--- 4 OpenAI SDK against the local stand-in")
            print("finish_reason:", result.choices[0].finish_reason)
            tool = result.choices[0].message.tool_calls[0]
            print("tool call:", tool.function.name, tool.function.arguments)
            print("usage:", result.usage.prompt_tokens, result.usage.completion_tokens, result.usage.total_tokens)
            # Exercise the follow-up through both SDKs, not just dictionaries.
            sdk_follow = deepcopy(WEATHER)
            sdk_follow["messages"] += [result.choices[0].message.model_dump(exclude_unset=True), deepcopy(TOOL_RESULT)]
            assert client.chat.completions.create(**sdk_follow).choices[0].finish_reason == "stop"

        overload = True
        try:
            send(WEATHER)
        except APIStatusError as exc:
            assert exc.status_code == 529
            # Deliberate demo policy, not a provider-standard status mapping.
            mapped = {"status": 502, "error": exc.response.json()["error"]}
        else:
            raise AssertionError("Expected the synthetic 529")
        show("--- 5a leg 1 Anthropic error fixture (HTTP 529) mapped to a gateway status", mapped)
        failover = mapped["status"] in [429, 500, 502, 503, 504]
        print("5b failover on this status:", failover)
        if failover:
            leg2 = deepcopy(WEATHER)
            leg2["model"] = "gpt-5.6-sol"
            # Payload construction only: there is no second provider call.
            show("--- 5c leg 2 payload prepared for an OpenAI-format provider (same request, new model, no translation)", leg2)
    ORIGINAL_CONTENT.clear()


if __name__ == "__main__":
    main()
