#!/usr/bin/env python3
"""A fake `claude` for the suite. Reads CLAUDE_CONFIG_DIR like the real one.

--version                                   prints a version line
plugin marketplace add <dir> --json         copies <dir> to the config dir's plugin cache
plugin install bitranox@bitranox-skills --json   records the install
-p <prompt> ...                             replays FAKE_CLAUDE_STREAM (a stream.jsonl path) to
                                            stdout, writes a transcript under the config dir's
                                            projects/<cwd dashkey>/<session id>.jsonl as the real
                                            CLI does, and makes one commit in the cwd; then, when
                                            FAKE_CLAUDE_SCRIPT names a Python file, runs it in the
                                            cwd with stdout still open (a test's extra behaviour)
"""
import json
import os
import re
import runpy
import shutil
import subprocess
import sys
from pathlib import Path


def _write_transcript(cfg, stream_text):
    """One transcript line naming the session the replayed stream's init record gives."""
    first = json.loads(stream_text.splitlines()[0]) if stream_text.strip() else {}
    session = first.get("session_id") or "fake-session"
    project = cfg / "projects" / re.sub(r"[^a-zA-Z0-9]", "-", os.getcwd())
    project.mkdir(parents=True, exist_ok=True)
    (project / f"{session}.jsonl").write_text(
        json.dumps({"type": "user", "message": {"content": "fake transcript of " + session}}) + "\n", encoding="utf-8")


def main(argv):
    cfg = Path(os.environ["CLAUDE_CONFIG_DIR"])
    if argv[:1] == ["--version"]:
        print("9.9.9 (fake)")
        return 0
    if argv[:3] == ["plugin", "marketplace", "add"]:
        src = Path(argv[3])
        version = json.loads((src / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8"))["version"]
        dst = cfg / "plugins" / "cache" / "bitranox-skills" / "bitranox" / version
        if dst.exists():
            shutil.rmtree(dst)
        shutil.copytree(src, dst, ignore=shutil.ignore_patterns(".git"))
        (cfg / "plugins").mkdir(parents=True, exist_ok=True)
        (cfg / "plugins" / "installed_plugins.json").write_text(json.dumps(
            {"version": 2, "plugins": {"bitranox@bitranox-skills": [{"installPath": str(dst)}]}}),
            encoding="utf-8")
        print(json.dumps({"ok": True}))
        return 0
    if argv[:2] == ["plugin", "install"]:
        print(json.dumps({"ok": True}))
        return 0
    if argv[:1] == ["-p"]:
        stream = Path(os.environ["FAKE_CLAUDE_STREAM"])
        text = stream.read_text(encoding="utf-8")
        sys.stdout.write(text)
        sys.stdout.flush()
        _write_transcript(cfg, text)
        Path("arm-work.txt").write_text("done by the fake arm\n", encoding="utf-8")
        env = dict(os.environ, GIT_AUTHOR_NAME="arm", GIT_AUTHOR_EMAIL="arm@x",
                   GIT_COMMITTER_NAME="arm", GIT_COMMITTER_EMAIL="arm@x")
        subprocess.run(["git", "add", "arm-work.txt"], check=True, env=env)
        subprocess.run(["git", "commit", "-q", "-m", "Task 1: arm work"], check=True, env=env)
        if os.environ.get("FAKE_CLAUDE_SCRIPT"):
            runpy.run_path(os.environ["FAKE_CLAUDE_SCRIPT"], run_name="__main__")
        return 0
    print(f"fake claude: unknown argv {argv}", file=sys.stderr)
    return 2


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
