#!/usr/bin/env python3
from __future__ import annotations

import json
import sys

_SECRET_FIXTURE = "sk" + "-" + "abcdefghijklmnop"


def emit(payload: dict) -> None:
    print(json.dumps(payload, separators=(",", ":")), flush=True)


def response(request: dict, result: dict) -> None:
    emit({"id": request.get("id"), "result": result})


def run_app_server() -> int:
    thread_id = "thread-mock-1"
    turn_id = "turn-mock-1"
    command = "echo " + _SECRET_FIXTURE
    for line in sys.stdin:
        request = json.loads(line)
        method = request.get("method")
        if method == "initialize":
            response(request, {})
        elif method == "thread/start":
            response(request, {"thread": {"id": thread_id}})
        elif method == "turn/start":
            response(request, {"turn": {"id": turn_id}})
            emit({"method": "thread/started", "params": {"threadId": thread_id}})
            emit({
                "method": "turn/started",
                "params": {"threadId": thread_id, "turn": {"id": turn_id, "status": "inProgress"}},
            })
            emit({
                "method": "item/started",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "id": "cmd-1",
                        "type": "commandExecution",
                        "command": command,
                        "status": "inProgress",
                    },
                },
            })
            emit({
                "method": "item/commandExecution/outputDelta",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "itemId": "cmd-1",
                    "delta": "done\n",
                },
            })
            emit({
                "method": "item/completed",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "id": "cmd-1",
                        "type": "commandExecution",
                        "command": command,
                        "exitCode": 0,
                        "status": "completed",
                    },
                },
            })
            emit({
                "method": "item/started",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "id": "file-1",
                        "type": "fileChange",
                        "changes": [{"path": "README.md", "kind": "update"}],
                        "status": "inProgress",
                    },
                },
            })
            emit({
                "method": "item/completed",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "id": "file-1",
                        "type": "fileChange",
                        "changes": [{"path": "README.md", "kind": "update"}],
                        "status": "completed",
                    },
                },
            })
            emit({
                "method": "item/started",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "id": "mcp-1",
                        "type": "mcpToolCall",
                        "server": "fs",
                        "tool": "read",
                        "arguments": {"path": "README.md"},
                        "status": "inProgress",
                    },
                },
            })
            emit({
                "method": "item/completed",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "id": "mcp-1",
                        "type": "mcpToolCall",
                        "server": "fs",
                        "tool": "read",
                        "arguments": {"path": "README.md"},
                        "result": {"ok": True},
                        "status": "completed",
                    },
                },
            })
            emit({
                "method": "item/started",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "id": "web-1",
                        "type": "webSearch",
                        "query": "Codex docs",
                        "status": "inProgress",
                    },
                },
            })
            emit({
                "method": "item/completed",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "id": "web-1",
                        "type": "webSearch",
                        "query": "Codex docs",
                        "status": "completed",
                    },
                },
            })
            emit({
                "method": "rawResponseItem/completed",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "item": {
                        "type": "message",
                        "role": "assistant",
                        "content": [{"type": "output_text", "text": "mock response"}],
                    },
                },
            })
            emit({
                "method": "thread/tokenUsage/updated",
                "params": {
                    "threadId": thread_id,
                    "turnId": turn_id,
                    "usage": {"inputTokens": 10, "cachedInputTokens": 3, "outputTokens": 4},
                },
            })
            emit({
                "method": "turn/completed",
                "params": {"threadId": thread_id, "turn": {"id": turn_id, "status": "completed"}},
            })
            return 0
    return 0


def main() -> int:
    args = sys.argv[1:]
    if not args:
        print("codex mock", file=sys.stderr)
        return 1
    if args[0] == "app-server":
        return run_app_server()
    if args[0] == "exec" and "--json" in args:
        command = "echo " + _SECRET_FIXTURE
        print('{"type":"thread.started","thread_id":"thread-mock-1"}')
        print('{"type":"turn.started","turn_id":"turn-mock-1","thread_id":"thread-mock-1"}')
        emit({
            "type": "item.started",
            "turn_id": "turn-mock-1",
            "item": {
                "id": "cmd-1",
                "type": "command_execution",
                "command": command,
                "status": "in_progress",
            },
        })
        emit({
            "type": "item.completed",
            "turn_id": "turn-mock-1",
            "item": {
                "id": "cmd-1",
                "type": "command_execution",
                "command": command,
                "aggregated_output": "done\n",
                "exit_code": 0,
                "status": "completed",
            },
        })
        print('{"type":"item.started","turn_id":"turn-mock-1","item":{"id":"file-1","type":"file_change","changes":[{"path":"README.md","kind":"update"}],"status":"in_progress"}}')
        print('{"type":"item.completed","turn_id":"turn-mock-1","item":{"id":"file-1","type":"file_change","changes":[{"path":"README.md","kind":"update"}],"status":"completed"}}')
        print('{"type":"item.started","turn_id":"turn-mock-1","item":{"id":"mcp-1","type":"mcp_tool_call","server":"fs","tool":"read","arguments":{"path":"README.md"},"status":"in_progress"}}')
        print('{"type":"item.completed","turn_id":"turn-mock-1","item":{"id":"mcp-1","type":"mcp_tool_call","server":"fs","tool":"read","arguments":{"path":"README.md"},"result":{"ok":true},"status":"completed"}}')
        print('{"type":"item.started","turn_id":"turn-mock-1","item":{"id":"web-1","type":"web_search","query":"Codex docs","status":"in_progress"}}')
        print('{"type":"item.completed","turn_id":"turn-mock-1","item":{"id":"web-1","type":"web_search","query":"Codex docs","status":"completed"}}')
        print('{"type":"turn.completed","turn_id":"turn-mock-1","thread_id":"thread-mock-1","usage":{"input_tokens":10,"cached_input_tokens":3,"output_tokens":4}}')
        return 0
    if args[0] == "exec":
        print(
            '{"output":"mock-cli-response","tool":"mock_tool",'
            '"primitives":["hook","skill","mcp","rule","read","write","tool"]}'
        )
        return 0
    print("unsupported", file=sys.stderr)
    return 2


if __name__ == "__main__":
    raise SystemExit(main())
