#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-only
"""Faux harnais "dsh" (DeepSeek Harness) du banc de test — n'appelle jamais dsh."""
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("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": "deepseek", "argv": args,
                                "compte": _compte()}) + "\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)
    session = "dsh-session-1"
    if "--session-id" in args:
        session = args[args.index("--session-id") + 1]
        # L166 : session fille refusée, comme `assertAdoptable` du vrai dsh
        if session in os.environ.get("AMEESH_TEST_DSH_CHILD_SESSIONS", "").split(","):
            message = ('session "%s" is a subagent or forked session and cannot be '
                       'driven directly' % session)
            print(json.dumps({"type": "error", "message": message}), flush=True)
            print("dsh: %s" % message, file=sys.stderr, flush=True)
            return 1
    print(json.dumps({"type": "session", "sessionId": session}), flush=True)
    print(json.dumps({"type": "text", "text": "bonjour du faux dsh (session %s)" % session}),
          flush=True)
    # Usage par étape (L60) : `AMEESH_TEST_DSH_USAGE=entrée,cache,sortie;…`,
    # une étape par triplet, comme le vrai flux (`status`/`step_end`).
    for numero, etape in enumerate(filter(None, os.environ.get(
            "AMEESH_TEST_DSH_USAGE", "").split(";")), start=1):
        entree, cache, sortie = (int(v) for v in etape.split(","))
        print(json.dumps({"type": "status", "phase": "step_end", "turn": 1, "step": numero,
                          "usage": {"inputTokens": entree, "cacheReadTokens": cache,
                                    "outputTokens": sortie, "cacheWriteTokens": 0,
                                    "totalTokens": entree + cache + sortie}}), flush=True)
    print(json.dumps({"type": "final", "text": "fini", "cost_usd": 0.002}), flush=True)
    return int(os.environ.get("AMEESH_TEST_EXIT", "0"))


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