#!/usr/bin/env python3
"""Fake herdr binary for the sandboxctl test suite (doc-derived).

Emits the doc-derived fixtures in this directory (see README.md) so the
default `uv run pytest` never needs a real herdr install. Behavior is
driven entirely by environment variables:

- ``FAKE_HERDR_FIXTURES``: directory holding the fixture JSON files
  (default: this script's directory).
- ``FAKE_HERDR_RECORD``: file to append one JSON line per invocation
  (``{"argv": [...]}``) so tests can assert on invocations.
- ``FAKE_HERDR_MODE``: one of ``ok`` (default), ``not_running``,
  ``binary_stale``, ``error``, ``syntax_error``, ``malformed``.
  Only ``status server --json`` consults the mode.
- ``FAKE_HERDR_VERSION``: version reported by ``--version``
  (default ``0.9.5``); set below the floor to test the version gate.

Simulated surface (mirrors the shapes captured in issue #313):

- ``herdr --version``                          -> ``herdr 0.9.5``
- ``herdr [--session N] status server --json`` -> fixture on stdout, exit 0
- ``herdr [...] workspace create ... --json``  -> fixture on stdout, exit 0
- ``herdr [...] workspace split ... --json``   -> fixture on stdout, exit 0
- ``herdr [...] pane run ...`` / ``send-text`` -> empty payload, exit 0
- anything else                                -> usage error on stderr, exit 2
"""

from __future__ import annotations

import json
import os
import sys
from pathlib import Path


def _fixtures_dir() -> Path:
    default = Path(__file__).resolve().parent
    return Path(os.environ.get("FAKE_HERDR_FIXTURES", default))


def _record(argv: list[str]) -> None:
    target = os.environ.get("FAKE_HERDR_RECORD")
    if not target:
        return
    with open(target, "a") as handle:
        handle.write(json.dumps({"argv": argv}) + "\n")


def _emit(fixture_name: str) -> int:
    payload = (_fixtures_dir() / fixture_name).read_text()
    sys.stdout.write(payload)
    return 0


def main(argv: list[str]) -> int:
    _record(argv)

    # Strip argv[0] (this script) and global flags (--session NAME) so
    # dispatch sees the subcommand.
    words: list[str] = []
    skip_next = False
    for word in argv[1:]:
        if skip_next:
            skip_next = False
            continue
        if word == "--session":
            skip_next = True
            continue
        words.append(word)

    if "--version" in words:
        sys.stdout.write(f"herdr {os.environ.get('FAKE_HERDR_VERSION', '0.9.5')}\n")
        return 0

    mode = os.environ.get("FAKE_HERDR_MODE", "ok")

    if words[:3] == ["status", "server", "--json"]:
        if mode == "not_running":
            return _emit("status-server-not-running.json")
        if mode == "binary_stale":
            return _emit("status-server-binary-stale.json")
        if mode == "error":
            sys.stderr.write((_fixtures_dir() / "error-server-not-running.json").read_text())
            return 1
        if mode == "syntax_error":
            sys.stderr.write("usage: herdr status server [--json]\n")
            return 2
        if mode == "malformed":
            sys.stdout.write("herdr: server status: not json{\n")
            return 0
        return _emit("status-server-running.json")

    if words[:2] == ["workspace", "create"]:
        return _emit("workspace-create.json")

    if words[:2] == ["workspace", "split"]:
        return _emit("workspace-split.json")

    if words[:2] == ["pane", "run"] or words[:1] == ["send-text"]:
        return 0  # payload-free verbs: empty stdout, exit 0

    sys.stderr.write(f"fake-herdr: unrecognized invocation: {words}\n")
    return 2


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