"""3 APIの要求、模擬SSE、読み取り専用ツールの結果を比べる。"""

import json

MODEL = "deepseek-flash"
PROMPT = "図書館の週末の開館時間を知りたい。"
HOURS = {"Saturday": "10:00–16:00", "Sunday": "12:00–16:00"}
FORMAT = {
    "chat": "/chat/completions",
    "responses": "/responses",
    "messages": "/anthropic/v1/messages",
}


def stream_request(wire):
    path = FORMAT[wire]
    turn = {"input": PROMPT} if wire == "responses" else {
        "messages": [{"role": "user", "content": PROMPT}]
    }
    limits = (
        {"max_output_tokens": 64, "reasoning": {"effort": "none"}}
        if wire == "responses"
        else {"max_tokens": 64, "thinking": {"type": "disabled"}}
    )
    body = {"model": MODEL, **turn, **limits, "stream": True}
    if wire == "chat":
        body["stream_options"] = {"include_usage": True}
    return path, body


def sse_data(lines):
    """UTF-8でデコードした行を受け取り、空行までのdataフィールドをまとめて返す。コメント行は読み飛ばす。"""
    data = []
    for raw_line in lines:
        line = raw_line.rstrip("\r\n")
        if not line:
            if data:
                yield "\n".join(data)
            data.clear()
        elif line.startswith("data:"):
            data.append(line.removeprefix("data:").removeprefix(" "))


def stream_result(wire, lines):
    text = []
    usage = None
    stop = None
    for data in sse_data(lines):
        if wire == "chat" and data == "[DONE]":
            if not stop:
                raise ValueError("完了理由を取得できませんでした")
            return "".join(text), usage
        packet = json.loads(data)
        kind = packet.get("type")
        if "error" in packet or kind in {"error", "response.failed", "response.incomplete"}:
            raise ValueError("ストリームがエラーまたは未完了で終了しました")
        if wire == "chat":
            for choice in packet.get("choices", []):
                if choice["index"] == 0:
                    text.append(choice.get("delta", {}).get("content") or "")
                    stop = choice.get("finish_reason") or stop
            if packet.get("usage") is not None:
                usage = packet["usage"]
        elif wire == "responses":
            if kind == "response.output_text.delta":
                text.append(packet["delta"])
            elif kind == "response.completed":
                return "".join(text), packet["response"].get("usage")
        elif wire == "messages":
            if kind == "content_block_delta" and packet["delta"]["type"] == "text_delta":
                text.append(packet["delta"]["text"])
            elif kind == "message_delta":
                usage = packet.get("usage")
                stop = packet["delta"].get("stop_reason")
            elif kind == "message_stop":
                if not stop:
                    raise ValueError("完了理由を取得できませんでした")
                return "".join(text), usage
    raise EOFError("完了イベントの前にストリームが閉じました")


def mock_sse(wire):
    """本文と完了判定に必要なイベントに絞った架空の会話。"""
    text = "週末の時間を確認します。"
    events = {
        "chat": [
            {"choices": [{"index": 0, "delta": {"content": text}, "finish_reason": None}]},
            {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
            {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], "usage": {"total_tokens": 20}},
            "[DONE]",
        ],
        "responses": [
            {"type": "response.output_text.delta", "sequence_number": 0, "delta": text},
            {"type": "response.completed", "sequence_number": 1, "response": {"usage": {"total_tokens": 20}}},
        ],
        "messages": [
            {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text}},
            {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"input_tokens": 15, "output_tokens": 5}},
            {"type": "message_stop"},
        ],
    }
    yield ": keep-alive\r\n"
    yield "\r\n"
    for event in events[wire]:
        if isinstance(event, dict) and "type" in event:
            yield f"event: {event['type']}\r\n"
        data = event if isinstance(event, str) else json.dumps(event, ensure_ascii=False)
        yield f"data: {data}\r\n"
        yield "\r\n"


def tool_request(wire):
    """同じ読み取り専用ツールを3形式の要求に組み込む。"""
    path, body = stream_request(wire)
    body.pop("stream_options", None)
    body["stream"] = False
    schema = {
        "type": "object",
        "properties": {"day": {"type": "string", "enum": list(HOURS)}},
        "required": ["day"],
        "additionalProperties": False,
    }
    function = {"name": "library_hours", "description": "週末の開館時間を返す"}
    if wire == "chat":
        tool = {"type": "function", "function": {**function, "parameters": schema}}
    elif wire == "responses":
        tool = {"type": "function", **function, "parameters": schema}
    else:
        tool = {**function, "input_schema": schema}
    body["tools"] = [tool]
    return path, body


def tool_result(wire, call_id, name, arguments):
    """準備済みの時間表を引くだけのツール。3形式に同じ呼び出しIDを返す。"""
    if name != "library_hours" or not isinstance(call_id, str) or not call_id:
        raise ValueError("許可されたツール名と呼び出しIDが必要です")
    values = json.loads(arguments) if isinstance(arguments, str) else arguments
    if not isinstance(values, dict) or set(values) != {"day"}:
        raise ValueError("引数には day が1つ必要です")
    day = values["day"]
    if not isinstance(day, str) or day not in HOURS:
        raise ValueError("day は Saturday または Sunday です")
    output = HOURS[day]
    if wire == "chat":
        return {"role": "tool", "tool_call_id": call_id, "content": output}
    if wire == "responses":
        return {"type": "function_call_output", "call_id": call_id, "output": output}
    if wire == "messages":
        return {"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": call_id, "content": output}
        ]}
    raise ValueError("未知の形式です")


def vision_request():
    """Responsesでの画像参照。例示用ドメインのURLは送信しない。"""
    return {
        "model": MODEL,
        "input": [{"role": "user", "content": [
            {"type": "input_text", "text": "写真の見出しを提案してください。"},
            {"type": "input_image", "image_url": "https://example.invalid/fixture.png"},
        ]}],
        "reasoning": {"effort": "none"},
        "max_output_tokens": 64,
    }


if __name__ == "__main__":
    for wire in FORMAT:
        print(wire, stream_request(wire))
        print("模擬応答", stream_result(wire, mock_sse(wire)))
        print("ツール付き要求", tool_request(wire))
        print("模擬ツール結果", tool_result(wire, "fixture-hours-1", "library_hours", '{"day":"Saturday"}'))
    print("画像入力の例", vision_request())
