"""Mock OpenAI Responses endpoint for reproducing #25891 against a real `codex app-server`.

Turn script: 1st sampling -> shell tool call, later samplings -> final answer "VERDICT: APPROVE".
Compaction requests (detected by the summarization prompt) -> a short summary.
Every response reports usage far above the configured auto-compact limit, standing in for
GPT-6.1-Sol's small auto-compact scope.
"""

import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

LOG = open(sys.argv[2], "a", buffering=1)
lock = threading.Lock()
state = {"n": 0}
TOOL = sys.argv[3] if len(sys.argv) > 3 else "exec_command"


def sse(handler, events):
    handler.send_response(200)
    handler.send_header("Content-Type", "text/event-stream")
    handler.end_headers()
    for ev in events:
        handler.wfile.write(f"event: {ev['type']}\ndata: {json.dumps(ev)}\n\n".encode())
    handler.wfile.flush()


def usage(body):
    tok = len(json.dumps(body.get("input", []))) // 4
    return {"input_tokens": tok, "output_tokens": 50, "total_tokens": tok + 50,
            "input_tokens_details": {"cached_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}}


def texts(body):
    out = []
    for item in body.get("input", []):
        for c in item.get("content", []) or []:
            if isinstance(c, dict) and "text" in c:
                out.append((item.get("role"), c["text"]))
    return out


class H(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(b'{"data":[],"models":[]}')

    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
        with lock:
            state["n"] += 1
            n = state["n"]
        t = texts(body)
        last_user = next((x for r, x in reversed(t) if r == "user"), "")
        is_compact = "checkpoint" in last_user.lower() or "summar" in last_user.lower() and "handoff" in last_user.lower()
        has_tool_output = any(i.get("type") == "function_call_output" for i in body.get("input", []))
        dev_markers = sum(1 for r, x in t if "T3_REPRO_CONTEXT" in x)
        LOG.write(json.dumps({"n": n, "path": self.path, "compact": is_compact, "items": len(body.get("input", [])),
                              "hasToolOutput": has_tool_output, "tok": len(json.dumps(body.get("input", []))) // 4, "tools": [t.get("name") for t in body.get("tools", [])][:12], "t3ContextCopies": dev_markers,
                              "lastUser": last_user[:80]}) + "\n")
        import time; time.sleep(float(sys.argv[4]) if len(sys.argv) > 4 else 0)
        rid = f"resp_{n}"
        created = {"type": "response.created", "response": {"id": rid}}
        if is_compact:
            item = {"type": "message", "role": "assistant", "id": f"msg_{n}",
                    "content": [{"type": "output_text", "text": "Summary: ran echo, answered VERDICT: APPROVE."}]}
        elif not has_tool_output and not any("Summary: ran echo" in x for _, x in t):
            item = {"type": "function_call", "id": f"fc_{n}", "call_id": f"call_{n}", "name": TOOL,
                    "arguments": json.dumps({"cmd": "echo hi", "command": ["echo", "hi"]})}
        else:
            item = {"type": "message", "role": "assistant", "id": f"msg_{n}",
                    "content": [{"type": "output_text", "text": "VERDICT: APPROVE"}]}
        sse(self, [created, {"type": "response.output_item.done", "item": item},
                   {"type": "response.completed", "response": {"id": rid, "usage": usage(body)}}])


ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
