#!/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 (it also records the prompt and the installed
                                            plugin's skill dirs), 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);
                                            with FAKE_CLAUDE_CWD_FROM_PROC set it first resolves its
                                            cwd through /proc/self/cwd and fails the way the real CLI
                                            does when it cannot (an empty /proc in a sandbox)
"""
import json
import os
import re
import runpy
import shutil
import subprocess
import sys
from pathlib import Path


def _installed_skills(cfg):
    """The skill dirs of the installed plugin, so a test can read what the session could load."""
    registry = cfg / "plugins" / "installed_plugins.json"
    if not registry.is_file():
        return []
    entries = json.loads(registry.read_text(encoding="utf-8"))["plugins"]["bitranox@bitranox-skills"]
    skills = Path(entries[0]["installPath"]) / "skills"
    return sorted(p.name for p in skills.iterdir()) if skills.is_dir() else []


def _write_transcript(cfg, stream_text, prompt):
    """One transcript line naming the session the replayed stream's init record gives, the prompt
    the session was given and the installed skills it could load."""
    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},
                    "prompt": prompt, "installed_skills": _installed_skills(cfg)}) + "\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"]:
        if os.environ.get("FAKE_CLAUDE_CWD_FROM_PROC"):
            try:
                os.readlink("/proc/self/cwd")
            except OSError as exc:
                print(f"Error: Can't access working directory via /proc/self/cwd: {exc}", file=sys.stderr)
                return 1
        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, argv[1])
        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:]))
