#!/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``.
  ``status server --json`` always consults the mode; in stateful mode
  (below) ``error`` additionally fails every lifecycle verb with the
  ``server_not_running`` envelope, simulating a herdr outage.
- ``FAKE_HERDR_VERSION``: version reported by ``--version``
  (default ``0.9.5``); set below the floor to test the version gate.
- ``FAKE_HERDR_STATE``: JSON file driving a *stateful* simulation of the
  workspace lifecycle verbs added in #315 (``workspace create/get/close/
  report-metadata``, ``pane process-info``). Unset (default) keeps the
  original stateless fixture behavior. The state is plain JSON so tests
  can script failures (kill a pane, drop a workspace) by editing the file:

  ``{"workspaces": {"ws-1": {"id": "ws-1", "name": "cockpit",
    "panes": [{"id": "pane-1", ...}]}, ...},
    "metadata": {"ws-1": {"source": "sandboxctl", "token": "..."}},
    "dead_panes": ["pane-2"], "seq": 3}``

- ``FAKE_HERDR_PANE_INFO_ERROR`` / ``FAKE_HERDR_METADATA_ERROR``: error
  codes (stateful mode only) that make ``pane process-info`` /
  ``workspace report-metadata`` fail with an error envelope carrying that
  code — for testing fail-closed handling of unknown states (#350).
- ``FAKE_HERDR_CURRENT_PANE``: the pane ``pane split --current`` splits
  (stateful mode; default: the first pane of the first workspace).
- ``FAKE_HERDR_SERVER_START_ERROR``: error code that makes ``server start``
  fail with an error envelope — for testing the cockpit's auto-start
  failure path (#314). ``FAKE_HERDR_SERVER_START_NOOP=1`` makes the start
  succeed without flipping readiness, for testing the ready-poll timeout.
- ``FAKE_HERDR_SERVER_READY_DELAY``: number of ``status server`` reads
  that still answer not-running after a successful ``server start`` — for
  testing the cockpit's bounded readiness poll.
- ``FAKE_HERDR_PANE_RUN_FAILS``: fail the first N ``pane run`` invocations
  with the ``FAKE_HERDR_PANE_RUN_ERROR`` code (default ``pane_not_ready``)
  — for testing the cockpit's run-check-retry-once behavior.
- ``FAKE_HERDR_EMPTY_CREATE=1``: create workspaces with no panes — for
  testing the cockpit's "created without panes" failure.

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 split ... --json``        -> fixture on stdout, exit 0
- ``herdr [...] pane run ...`` / ``send-text`` -> empty payload, exit 0
- ``herdr [...] server start`` / ``workspace focus <id>`` -> empty, exit 0
- anything else                                -> usage error on stderr, exit 2

Stateful additions (issue #315, same doc-derived shapes):

- ``workspace get <id> --json``                -> envelope, or
  ``workspace_not_found`` error envelope + exit 1
- ``workspace close <id>``                     -> empty payload, exit 0
  (``workspace_not_found`` + exit 1 when unknown)
- ``workspace report-metadata <id> --source S --token T`` -> empty, exit 0
- ``pane process-info <pane> --json``          -> liveness payload
  (``pane_not_found`` + exit 1 when the pane's workspace is gone)

Stateful additions (issue #314, same doc-derived shapes):

- ``server start``                             -> empty payload, exit 0;
  flips ``status server`` to running (state key ``server_running``),
  optionally delayed by ``FAKE_HERDR_SERVER_READY_DELAY`` reads
- ``workspace create --label <name> [--no-focus]`` -> envelope (label is an
  option in 0.9.5); ``--no-focus`` is reflected as ``focused: false``;
  ``FAKE_HERDR_EMPTY_CREATE=1`` creates a workspace with no panes
- ``pane split [--current|<pane>] --direction D --ratio R [--no-focus] --json``
  -> envelope with the new pane (``pane``), the split origin (``source``),
  and the workspace's panes; the new pane joins the state
- ``workspace focus <id>``                     -> empty payload, exit 0
  (``workspace_not_found`` + exit 1 when unknown)
- ``pane run <pane> -- <command...>``          -> empty payload, exit 0;
  commands are recorded under ``pane_runs`` in the state
"""

from __future__ import annotations

import json
import os
import re
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 _error(fixture_name: str) -> int:
    sys.stderr.write((_fixtures_dir() / fixture_name).read_text())
    return 1


def _emit_json(payload: object) -> int:
    sys.stdout.write(json.dumps(payload, indent=2) + "\n")
    return 0


# ---------------------------------------------------------------------------
# Stateful workspace simulation (issue #315)
# ---------------------------------------------------------------------------


def _empty_state() -> dict:
    return {"workspaces": {}, "metadata": {}, "dead_panes": [], "seq": 0}


def _load_state() -> dict:
    target = os.environ.get("FAKE_HERDR_STATE")
    if not target:
        return _empty_state()
    path = Path(target)
    if not path.exists():
        return _empty_state()
    return json.loads(path.read_text())


def _save_state(state: dict) -> None:
    target = os.environ.get("FAKE_HERDR_STATE")
    if target:
        Path(target).write_text(json.dumps(state, indent=2) + "\n")


def _workspace_envelope(state: dict, workspace: dict, *, focused: bool = True) -> dict:
    """Layout envelope for a stateful workspace (unknown fields included)."""
    return {
        "id": workspace["id"],
        "name": workspace["name"],
        "panes": [dict(pane) for pane in workspace["panes"]],
        "socket": "/home/agent/.config/herdr/sessions/default/herdr.sock",
        "created_at": workspace.get("created_at", "2026-12-03T10:00:00Z"),
        "focused": focused,
    }


def _positional(words: list[str], index: int) -> str | None:
    """The argument at ``index`` when it exists and is not an option."""
    if len(words) > index and not words[index].startswith("-"):
        return words[index]
    return None


def _env_count(name: str) -> int:
    try:
        return int(os.environ.get(name, "0") or "0")
    except ValueError:
        return 0


def _next_seq(state: dict) -> int:
    """The next ws-N/pane-N id suffix, never colliding with existing ids.

    The recorded ``seq`` is only a floor: seeded workspaces (in-pane tests)
    may already hold high pane ids, so the highest suffix actually in use
    wins (#351 review: a split must never mint a pane id that already
    exists in another workspace).
    """
    highest = state.get("seq", 0)
    for workspace in state.get("workspaces", {}).values():
        identifiers = [workspace.get("id", "")] + [pane.get("id", "") for pane in workspace.get("panes", [])]
        for identifier in identifiers:
            match = re.search(r"-(\d+)$", identifier)
            if match:
                highest = max(highest, int(match.group(1)))
    highest += 1
    state["seq"] = highest
    return highest


def _stateful_pane_split(words: list[str], state: dict, workspaces: dict) -> int:
    """``pane split [--current|<pane>] --direction D --ratio R [--no-focus] --json``.

    Doc-derived #314 shape: the envelope answers with the new pane under
    ``pane``, the split origin under ``source``, and the workspace's panes;
    the new pane joins the state so ``workspace get`` / ``pane
    process-info`` see the 2-pane cockpit.
    """
    if "--current" in words:
        source = os.environ.get("FAKE_HERDR_CURRENT_PANE") or state.get("current_pane")
        if source is None:
            first = next(iter(workspaces.values()), None)
            source = first["panes"][0]["id"] if first and first["panes"] else None
    else:
        source = _positional(words, 2)
    owner = None
    if source is not None:
        for workspace in workspaces.values():
            if any(pane.get("id") == source for pane in workspace["panes"]):
                owner = workspace
                break
    if owner is None:
        return _error("error-pane-not-found.json")
    new_pane = {"id": f"pane-{_next_seq(state)}", "title": owner["name"], "active": False}
    owner["panes"].append(new_pane)
    _save_state(state)
    return _emit_json(
        {
            "pane": new_pane["id"],
            "source": source,
            "direction": _option_value(words, "--direction") or "right",
            "ratio": _option_value(words, "--ratio") or "0.38",
            "workspace": owner["id"],
            "panes": [dict(pane) for pane in owner["panes"]],
            "hint": "extra fields are tolerated",
        }
    )


def _fail_with(code: str) -> int:
    """Emit a stderr JSON error envelope with the given code, exit 1."""
    sys.stderr.write(
        json.dumps({"id": "req-simulated", "error": {"code": code, "message": f"simulated {code} failure"}}) + "\n"
    )
    return 1


def _stateful(words: list[str]) -> int | None:
    """Handle the #315/#314 lifecycle verbs against FAKE_HERDR_STATE.

    Returns None when the invocation is not one of those verbs (so the
    stateless fixture dispatch stays authoritative for everything else),
    or when FAKE_HERDR_STATE is unset: the stateful simulation is
    opt-in, and ``workspace create`` must keep its stateless fixture
    answer for the #313 tests.
    """
    if not os.environ.get("FAKE_HERDR_STATE"):
        return None
    if os.environ.get("FAKE_HERDR_MODE") == "error":
        # Simulated outage: every lifecycle verb fails with the
        # server_not_running envelope, like a herdr server that died.
        return _error("error-server-not-running.json")
    state = _load_state()
    workspaces: dict = state["workspaces"]

    # ── #314: server lifecycle ────────────────────────────────────────────
    if words[:2] == ["server", "start"]:
        failure = os.environ.get("FAKE_HERDR_SERVER_START_ERROR")
        if failure:
            return _fail_with(failure)
        if not os.environ.get("FAKE_HERDR_SERVER_START_NOOP"):
            state["server_running"] = True
            state["server_pending_checks"] = _env_count("FAKE_HERDR_SERVER_READY_DELAY")
            _save_state(state)
        return 0  # payload-free verb

    if words[:3] == ["status", "server", "--json"] and state.get("server_running"):
        pending = state.get("server_pending_checks", 0)
        if pending > 0:
            # The server is binding its socket: still not running, by design.
            state["server_pending_checks"] = pending - 1
            _save_state(state)
            return None  # fall through to the mode-driven stateless answer
        # The auto-started server answers readiness as data.
        return _emit("status-server-running.json")
    # ... otherwise fall through to the mode-driven stateless answer.

    # ── #314: pane split / pane run / workspace focus ─────────────────────
    if words[:2] == ["pane", "split"]:
        return _stateful_pane_split(words, state, workspaces)

    if words[:2] == ["pane", "run"]:
        budget = state.setdefault("pane_run_failures_left", _env_count("FAKE_HERDR_PANE_RUN_FAILS"))
        if budget > 0:
            state["pane_run_failures_left"] = budget - 1
            _save_state(state)
            return _fail_with(os.environ.get("FAKE_HERDR_PANE_RUN_ERROR", "pane_not_ready"))
        pane_id = words[2] if len(words) > 2 else ""
        command = words[words.index("--") + 1 :] if "--" in words else []
        state.setdefault("pane_runs", {}).setdefault(pane_id, []).append(command)
        _save_state(state)
        return 0  # payload-free verb

    if words[:2] == ["workspace", "focus"]:
        workspace_id = words[2] if len(words) > 2 else ""
        if workspace_id not in workspaces:
            return _error("error-workspace-not-found.json")
        state["focused_workspace"] = workspace_id
        _save_state(state)
        return 0  # payload-free verb

    if words[:2] == ["workspace", "create"]:
        seq = _next_seq(state)
        name = _option_value(words, "--label") or _positional(words, 2) or "cockpit"
        workspace = {
            "id": f"ws-{seq}",
            "name": name,
            "panes": []
            if os.environ.get("FAKE_HERDR_EMPTY_CREATE")
            else [{"id": f"pane-{seq}", "title": name, "active": True}],
        }
        workspaces[workspace["id"]] = workspace
        _save_state(state)
        return _emit_json(_workspace_envelope(state, workspace, focused="--no-focus" not in words))

    if words[:2] == ["workspace", "get"]:
        workspace_id = words[2] if len(words) > 2 else ""
        workspace = workspaces.get(workspace_id)
        if workspace is None:
            return _error("error-workspace-not-found.json")
        return _emit_json(_workspace_envelope(state, workspace))

    if words[:2] == ["workspace", "close"]:
        workspace_id = words[2] if len(words) > 2 else ""
        if workspace_id not in workspaces:
            return _error("error-workspace-not-found.json")
        del workspaces[workspace_id]
        state.get("metadata", {}).pop(workspace_id, None)
        _save_state(state)
        return 0  # payload-free verb

    if words[:2] == ["workspace", "report-metadata"]:
        failure = os.environ.get("FAKE_HERDR_METADATA_ERROR")
        if failure:
            return _fail_with(failure)
        workspace_id = words[2] if len(words) > 2 else ""
        if workspace_id not in workspaces:
            return _error("error-workspace-not-found.json")
        source = _option_value(words, "--source")
        token = _option_value(words, "--token")
        state.setdefault("metadata", {})[workspace_id] = {"source": source, "token": token}
        _save_state(state)
        return 0  # payload-free verb

    if words[:2] == ["pane", "process-info"]:
        failure = os.environ.get("FAKE_HERDR_PANE_INFO_ERROR")
        if failure:
            return _fail_with(failure)
        pane_id = words[2] if len(words) > 2 else ""
        owner = None
        for workspace in workspaces.values():
            if any(pane.get("id") == pane_id for pane in workspace["panes"]):
                owner = workspace
                break
        if owner is None:
            return _error("error-pane-not-found.json")
        if pane_id in state.get("missing_panes", []):
            # Listed by the workspace envelope but unknown to herdr's pane
            # registry: process-info answers pane_not_found.
            return _error("error-pane-not-found.json")
        if pane_id in state.get("dead_panes", []):
            return _emit_json({"pane": pane_id, "alive": False, "process": None, "exit_code": 137})
        return _emit_json(
            {
                "pane": pane_id,
                "alive": True,
                "process": {"pid": 4800 + int(pane_id.rsplit("-", 1)[-1]), "state": "running"},
                "hint": "extra fields are tolerated",
            }
        )

    return None


def _option_value(words: list[str], flag: str) -> str | None:
    if flag in words:
        index = words.index(flag)
        if index + 1 < len(words):
            return words[index + 1]
    return None


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

    # Stateful #315 verbs first (opt-in via FAKE_HERDR_STATE, see
    # _stateful): the #313 verbs keep their stateless fixture answers.
    stateful = _stateful(words)
    if stateful is not None:
        return stateful

    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", "split"]:
        return _emit("pane-split.json")

    if words[:2] == ["server", "start"] or words[:2] == ["workspace", "focus"]:
        return 0  # payload-free verbs

    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))
