#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-only
"""Faux harnais "codex" du banc de test — n'appelle jamais Codex CLI."""
import json
import os
import signal
import sys
import time


def _compte() -> dict:
    """Le compte vu par le harnais (L30) : dossiers, et l'EMPREINTE de la clé
    (jamais la clé, même factice)."""
    import hashlib
    cle = os.environ.get("DEEPSEEK_API_KEY")
    return {
        "CLAUDE_CONFIG_DIR": os.environ.get("CLAUDE_CONFIG_DIR"),
        "CODEX_HOME": os.environ.get("CODEX_HOME"),
        "DSH_HOME": os.environ.get("DSH_HOME"),
        "cle": hashlib.sha256(cle.encode()).hexdigest()[:12] if cle else None,
    }


def main() -> int:
    args = sys.argv[1:]
    if args == ["--version"]:  # L120: read by the runner, not a turn
        print("codex-cli 9.9.9")
        return 0
    log = os.environ.get("AMEESH_TEST_LOG")
    if log:
        with open(log, "a", encoding="utf-8") as fh:
            fh.write(json.dumps({
                "harness": "codex", "argv": args, "compte": _compte(),
                "env": {k: os.environ.get(k) for k in (
                    "AGENT_MAIL_NAME", "AMEESH_RUNNER_ID", "AGENT_MESH_RUNNER_ID",
                    "AMEESH_LEASE_EPOCH", "AGENT_MESH_LEASE_EPOCH",
                    "AMEESH_HOST", "AMEESH_SCHEMA")},
            }) + "\n")
    if os.environ.get("AMEESH_TEST_SLEEP"):
        time.sleep(float(os.environ["AMEESH_TEST_SLEEP"]))
    if os.environ.get("AMEESH_TEST_KILL_SELF"):
        os.kill(os.getpid(), signal.SIGKILL)
    thread = "codex-thread-1"
    if "resume" in args:
        thread = args[args.index("resume") + 1]
    print(json.dumps({"type": "thread.started", "thread_id": thread}), flush=True)
    # L218 : AMEESH_TEST_MESSAGES, liste JSON des messages de l'agent du tour
    messages = json.loads(os.environ.get("AMEESH_TEST_MESSAGES") or "null")
    for texte in messages if messages is not None else [
            "bonjour du faux codex (fil %s)" % thread]:
        print(json.dumps({"type": "item.completed", "item": {
            "type": "agent_message", "text": texte}}), flush=True)
    print(json.dumps({"type": "turn.completed", "usage": {"input_tokens": 10,
                                                          "output_tokens": 5}}), flush=True)
    return int(os.environ.get("AMEESH_TEST_EXIT", "0"))


if __name__ == "__main__":
    sys.exit(main())
