#!/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).

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

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

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 _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) -> 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": True,
    }


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 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"]

    if words[:2] == ["workspace", "create"]:
        state["seq"] = state.get("seq", 0) + 1
        seq = state["seq"]
        name = words[2] if len(words) > 2 and not words[2].startswith("-") else "cockpit"
        workspace = {
            "id": f"ws-{seq}",
            "name": name,
            "panes": [{"id": f"pane-{seq}", "title": name, "active": True}],
        }
        workspaces[workspace["id"]] = workspace
        _save_state(state)
        return _emit_json(_workspace_envelope(state, workspace))

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