#!/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 main() -> int:
    args = sys.argv[1:]
    if not args:
        print("codex mock", file=sys.stderr)
        return 1
    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())
