#!/usr/bin/env python3
"""Stand-in for `codex exec --json` that follows the real JSONL protocol."""

import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _common import emit, log_call, opt, reject_flags, reply_text, sample, tool_reply  # noqa: E402

args = sys.argv[1:]
if args[:1] != ["exec"]:
    sys.exit(2)
if "--help" in args:
    print("Usage: codex exec [OPTIONS] [PROMPT]\n  --ephemeral\n  --output-schema <FILE>\n  --json")
    sys.exit(0)

reject_flags(args, "error: unexpected argument '{flag}' found")
prompt = sys.stdin.read()
images = [args[i + 1] for i, a in enumerate(args) if a == "--image"]
schema_path = opt(args, "--output-schema")
schema = json.load(open(schema_path)) if schema_path else None
log_call({"cli": "codex", "argv": args, "prompt": prompt, "images": len(images), "cwd": os.getcwd(),
          "schema": schema, "env_has_openai_key": "OPENAI_API_KEY" in os.environ})

model = opt(args, "--model") or "gpt-default"
emit({"type": "thread.started", "thread_id": "thread-1"})
emit({"type": "turn.started"})
if "FAIL" in prompt:
    emit({"type": "error", "message": "Reconnecting... 1/5"})
    emit({"type": "turn.failed", "error": {"message": "You've hit your usage limit."}})
    sys.exit(1)

emit({"type": "item.completed", "item": {"id": "item_0", "type": "reasoning", "text": "**Thinking**"}})
if opt(args, "--sandbox") != "read-only":
    emit({"type": "item.started", "item": {"id": "item_1", "type": "command_execution", "command": "bash -lc ls",
                                            "aggregated_output": "", "exit_code": None, "status": "in_progress"}})
    emit({"type": "item.completed", "item": {"id": "item_1", "type": "command_execution", "command": "bash -lc ls",
                                              "aggregated_output": "README.md\n", "exit_code": 0, "status": "completed"}})
    emit({"type": "item.completed", "item": {"id": "item_2", "type": "agent_message", "text": "Checked the files."}})

if schema and "tool_calls" in (schema.get("properties") or {}):
    names = schema["properties"]["tool_calls"]["items"]["properties"]["name"]["enum"]
    text = json.dumps(tool_reply(prompt, names, args_as_string=True))
elif schema:
    text = json.dumps(sample(schema))
else:
    text = reply_text(model, prompt)
emit({"type": "item.completed", "item": {"id": "item_3", "type": "agent_message", "text": text}})
emit({"type": "turn.completed", "usage": {"input_tokens": 120, "cached_input_tokens": 20, "output_tokens": 9,
                                         "reasoning_output_tokens": 4}})
