from __future__ import annotations

import json
import os
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import cdx
import command_router
from health_client import AccountSnapshot, HealthStatus


def write_rules(base_dir: Path) -> None:
    tray_dir = base_dir / ".local/state/overdeck/systray/runtime"
    write_rules_to(tray_dir)


def write_rules_to(tray_dir: Path) -> None:
    tray_dir.mkdir(parents=True, exist_ok=True)
    (tray_dir / "routing_rules.json").write_text(
        json.dumps(
            {
                "projects": {"zync.is": "avi", "automixer": "rafa", "multideal": "roy"},
                "default": "rafa",
                "fallback_chain": ["roy", "avi"],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            }
        ),
        encoding="utf-8",
    )


def install_capture_run(
    monkeypatch: pytest.MonkeyPatch, call: dict[str, object], returncode: int = 0
) -> None:
    def fake_supervise(
        argv: list[str], env: dict[str, str], log_path: object, **kwargs: object
    ) -> int:
        call["file"] = argv[0]
        call["args"] = argv
        call["env"] = env
        return returncode

    monkeypatch.setattr(command_router, "supervise", fake_supervise)


def write_health(base_dir: Path, payload: dict[str, dict[str, object]]) -> None:
    tray_dir = base_dir / ".local/state/overdeck/systray/runtime"
    tray_dir.mkdir(parents=True, exist_ok=True)
    (tray_dir / "health_cache.json").write_text(json.dumps(payload), encoding="utf-8")


@pytest.fixture
def base_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    monkeypatch.setattr(command_router.Path, "home", lambda: tmp_path)
    monkeypatch.setattr(command_router.remote_dispatch, "in_container", lambda: True)
    write_rules(tmp_path)
    for slug in ("avi", "rafa", "roy"):
        (tmp_path / ".local/state/overdeck/systray/runtime" / "accounts" / slug / "CODEX_HOME").mkdir(parents=True)
    (tmp_path / ".local/state/overdeck/systray/runtime" / "health_cache.json").write_text("{}", encoding="utf-8")
    return tmp_path


def test_main_execs_project_override_account(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    project_dir = base_dir / "src" / "zync.is"
    project_dir.mkdir(parents=True)
    write_health(
        base_dir,
        {
            "avi": {"status": "ok", "primary_used_pct": 12, "secondary_used_pct": 34},
            "rafa": {"status": "ok", "primary_used_pct": 1, "secondary_used_pct": 2},
        },
    )
    exec_call: dict[str, object] = {}

    monkeypatch.setattr(cdx, "detect_project_name", lambda cwd=None: "zync.is")
    install_capture_run(monkeypatch, exec_call)

    exit_code = cdx.main(["cdx", "exec", "--help"])

    assert exit_code == 0
    assert exec_call["file"] == "codex"
    assert exec_call["args"] == [
        "codex",
        "exec",
        "--sandbox",
        "danger-full-access",
        "--skip-git-repo-check",
        "--help",
    ]
    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "avi" / "CODEX_HOME"
    )
    assert exec_call["env"]["CODEX_SQLITE_HOME"] == str(
        base_dir
        / ".local/state/overdeck/systray/runtime"
        / "accounts"
        / "avi"
        / "SQLITE_HOME"
    )


def test_main_execs_default_account_when_project_unmatched(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    write_health(
        base_dir,
        {
            "rafa": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
    )
    exec_call: dict[str, object] = {}

    monkeypatch.setattr(cdx, "detect_project_name", lambda cwd=None: "unknown-project")

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["file"] = file
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    with pytest.raises(SystemExit):
        cdx.main(["cdx", "chat"])

    assert exec_call["args"] == ["codex", "chat"]
    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "rafa" / "CODEX_HOME"
    )


def test_main_uses_tray_selected_default_when_project_unmatched(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    (base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "avi" / "CODEX_HOME").mkdir(
        parents=True, exist_ok=True
    )
    (base_dir / ".local/state/overdeck/systray/runtime" / "default_slug").write_text("avi\n", encoding="utf-8")
    write_health(
        base_dir,
        {
            "avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
    )
    exec_call: dict[str, object] = {}

    monkeypatch.setattr(cdx, "detect_project_name", lambda cwd=None: "unknown-project")

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    with pytest.raises(SystemExit):
        cdx.main(["cdx", "chat"])

    assert exec_call["args"] == ["codex", "chat"]
    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "avi" / "CODEX_HOME"
    )


def test_main_uses_tray_selected_default_over_project_route(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    (base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "rafa" / "CODEX_HOME").mkdir(
        parents=True, exist_ok=True
    )
    (base_dir / ".local/state/overdeck/systray/runtime" / "default_slug").write_text("rafa\n", encoding="utf-8")
    write_health(
        base_dir,
        {
            "avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
            "rafa": {"status": "ok", "primary_used_pct": 30, "secondary_used_pct": 40},
        },
    )
    exec_call: dict[str, object] = {}

    monkeypatch.setattr(cdx, "detect_project_name", lambda cwd=None: "zync.is")

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    with pytest.raises(SystemExit):
        cdx.main(["cdx", "chat"])

    assert exec_call["args"] == ["codex", "chat"]
    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "rafa" / "CODEX_HOME"
    )


def test_main_uses_latest_legacy_tray_selected_default(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    new_tray = base_dir / ".local/state/overdeck/systray/runtime"
    legacy_tray = base_dir / ".codex-tray"
    (new_tray / "accounts" / "avi" / "CODEX_HOME").mkdir(parents=True, exist_ok=True)
    (legacy_tray / "accounts" / "rafa" / "CODEX_HOME").mkdir(
        parents=True, exist_ok=True
    )
    write_rules_to(legacy_tray)
    (new_tray / "default_slug").write_text("avi\n", encoding="utf-8")
    (legacy_tray / "default_slug").write_text("rafa\n", encoding="utf-8")
    monkeypatch.setattr(
        command_router.os.path,
        "getmtime",
        lambda path: 2.0 if ".codex-tray" in str(path) else 1.0,
    )
    write_health(
        base_dir,
        {
            "avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
    )
    (legacy_tray / "health_cache.json").write_text(
        json.dumps(
            {
                "rafa": {"status": "ok", "primary_used_pct": 30, "secondary_used_pct": 40},
            }
        ),
        encoding="utf-8",
    )
    exec_call: dict[str, object] = {}

    monkeypatch.setattr(cdx, "detect_project_name", lambda cwd=None: "zync.is")

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    with pytest.raises(SystemExit):
        cdx.main(["cdx", "chat"])

    assert exec_call["args"] == ["codex", "chat"]
    assert exec_call["env"]["CODEX_HOME"] == str(
        legacy_tray / "accounts" / "rafa" / "CODEX_HOME"
    )


def test_main_uses_tray_selected_default_when_quota_cache_is_exhausted(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    (base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "rafa" / "CODEX_HOME").mkdir(
        parents=True, exist_ok=True
    )
    (base_dir / ".local/state/overdeck/systray/runtime" / "default_slug").write_text("rafa\n", encoding="utf-8")
    write_health(
        base_dir,
        {
            "rafa": {"status": "ok", "primary_used_pct": 100, "secondary_used_pct": 79},
            "roy": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
            "avi": {"status": "ok", "primary_used_pct": 30, "secondary_used_pct": 40},
        },
    )
    exec_call: dict[str, object] = {}
    popen_calls: list[list[str]] = []

    monkeypatch.setattr(cdx, "detect_project_name", lambda cwd=None: "zync.is")

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    def fake_popen(args: list[str]) -> object:
        popen_calls.append(args)
        return object()

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
    monkeypatch.setattr(command_router.subprocess, "Popen", fake_popen)

    with pytest.raises(SystemExit):
        cdx.main(["cdx", "chat"])

    assert exec_call["args"] == ["codex", "chat"]
    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "rafa" / "CODEX_HOME"
    )


def test_load_health_returns_fresh_snapshots_without_warning(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    cache_path = tmp_path / "health_cache.json"
    cache_path.write_text(
        json.dumps(
            {
                "rafa": {"status": "ok", "primary_used_pct": 12, "secondary_used_pct": 34}
            }
        ),
        encoding="utf-8",
    )
    os.utime(cache_path, (1000.0, 1000.0))
    monkeypatch.setattr("health_store.time.time", lambda: 1060.0)

    snapshots = cdx.load_health(cache_path)

    assert snapshots == {
        "rafa": AccountSnapshot(HealthStatus.OK, 12, 34)
    }
    assert capsys.readouterr().err == ""


def test_load_health_warns_and_returns_empty_for_stale_cache(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    cache_path = tmp_path / "health_cache.json"
    cache_path.write_text(
        json.dumps(
            {
                "rafa": {"status": "ok", "primary_used_pct": 12, "secondary_used_pct": 34}
            }
        ),
        encoding="utf-8",
    )
    os.utime(cache_path, (1000.0, 1000.0))
    monkeypatch.setattr("health_store.time.time", lambda: 8201.0)

    assert cdx.load_health(cache_path) == {}
    assert capsys.readouterr().err.strip() == (
        "cdx: health cache missing or stale; proceeding without health data"
    )


def test_main_notifies_and_uses_fallback_for_broken_default(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    write_health(
        base_dir,
        {
            "rafa": {"status": "broken", "primary_used_pct": None, "secondary_used_pct": None},
            "roy": {"status": "ok", "primary_used_pct": 33, "secondary_used_pct": 44},
        },
    )
    exec_call: dict[str, object] = {}
    popen_calls: list[list[str]] = []

    monkeypatch.setattr(cdx, "detect_project_name", lambda cwd=None: "unknown-project")
    install_capture_run(monkeypatch, exec_call)

    def fake_popen(args: list[str]) -> object:
        popen_calls.append(args)
        return object()

    monkeypatch.setattr(command_router.subprocess, "Popen", fake_popen)

    cdx.main(["cdx", "exec"])

    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "roy" / "CODEX_HOME"
    )
    assert popen_calls == [["notify-send", "cdx", "rafa unavailable, using roy instead"]]


def test_main_execs_explicit_account_override_bypassing_routing(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    (base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "roy" / "CODEX_HOME").mkdir(
        parents=True, exist_ok=True
    )
    exec_call: dict[str, object] = {}

    def fail_detect_project_name(cwd: Path | None = None) -> str:
        raise AssertionError("routing must not run when --account is given")

    monkeypatch.setattr(cdx, "detect_project_name", fail_detect_project_name)

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["file"] = file
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    with pytest.raises(SystemExit) as exc:
        cdx.main(["cdx", "--account=roy", "chat"])

    assert exc.value.code == 0
    assert exec_call["args"] == ["codex", "chat"]
    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "roy" / "CODEX_HOME"
    )


def test_main_account_override_with_space_separated_value(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    (base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "rafa" / "CODEX_HOME").mkdir(
        parents=True, exist_ok=True
    )
    exec_call: dict[str, object] = {}
    install_capture_run(monkeypatch, exec_call)

    cdx.main(["cdx", "--account", "rafa", "exec"])

    assert exec_call["args"] == [
        "codex",
        "exec",
        "--sandbox",
        "danger-full-access",
        "--skip-git-repo-check",
    ]
    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "rafa" / "CODEX_HOME"
    )
    assert exec_call["env"]["CODEX_SQLITE_HOME"] == str(
        base_dir
        / ".local/state/overdeck/systray/runtime"
        / "accounts"
        / "rafa"
        / "SQLITE_HOME"
    )


def test_main_profile_override_selects_account_without_forwarding_profile_args(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    (base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "avi" / "CODEX_HOME").mkdir(
        parents=True, exist_ok=True
    )
    exec_call: dict[str, object] = {}

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    with pytest.raises(SystemExit):
        cdx.main(["cdx", "--profile", "avi", "chat"])

    assert exec_call["args"] == ["codex", "chat"]
    assert exec_call["env"]["CODEX_HOME"] == str(
        base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "avi" / "CODEX_HOME"
    )


def test_main_profile_resume_shares_sessions_across_accounts(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    accounts_dir = base_dir / ".local/state/overdeck/systray/runtime" / "accounts"
    rafa_home = accounts_dir / "rafa" / "CODEX_HOME"
    roy_home = accounts_dir / "roy" / "CODEX_HOME"
    session_id = "019f2033-9675-7992-8a15-f28b14627e1a"
    session_path = Path(
        f"2026/07/02/rollout-2026-07-02T07-21-19-{session_id}.jsonl"
    )
    rafa_session = rafa_home / "sessions" / session_path
    rafa_session.parent.mkdir(parents=True)
    rafa_session.write_text(f'{{"session":"{session_id}"}}\n', encoding="utf-8")
    (roy_home / "sessions").mkdir(parents=True)
    exec_call: dict[str, object] = {}

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    with pytest.raises(SystemExit):
        cdx.main(["cdx", "--profile", "roy", "resume", session_id])

    assert exec_call["args"] == ["codex", "resume", session_id]
    assert exec_call["env"]["CODEX_HOME"] == str(roy_home)
    assert (rafa_home / "sessions").is_symlink()
    assert (roy_home / "sessions").is_symlink()
    assert (roy_home / "sessions" / session_path).read_text(encoding="utf-8") == (
        f'{{"session":"{session_id}"}}\n'
    )


def test_main_rejects_unknown_account_override(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    exec_called = False

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        nonlocal exec_called
        exec_called = True

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    exit_code = cdx.main(["cdx", "--account=ghost", "chat"])

    assert exit_code == 1
    assert exec_called is False


def test_main_returns_one_and_reports_all_candidates_when_none_are_healthy(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    write_health(
        base_dir,
        {
            "rafa": {"status": "broken", "primary_used_pct": None, "secondary_used_pct": None},
            "roy": {"status": "ok", "primary_used_pct": 100, "secondary_used_pct": 10},
            "avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 100},
        },
    )
    exec_called = False

    monkeypatch.setattr(cdx, "detect_project_name", lambda cwd=None: "unknown-project")

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        nonlocal exec_called
        exec_called = True
        raise AssertionError("execvpe should not be called")

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    exit_code = cdx.main(["cdx", "exec"])
    captured = capsys.readouterr()

    assert exit_code == 1
    assert exec_called is False
    assert "rafa=broken" in captured.err
    assert "roy=quota-exhausted" in captured.err
    assert "avi=quota-exhausted" in captured.err


def test_load_health_reads_optional_reset_timestamps(tmp_path: Path) -> None:
    cache_path = tmp_path / "health_cache.json"
    cache_path.write_text(
        json.dumps(
            {
                "rafa": {
                    "status": "ok",
                    "primary_used_pct": 12,
                    "secondary_used_pct": 34,
                    "primary_reset_at": 1782907200,
                    "secondary_reset_at": 1783382400,
                }
            }
        ),
        encoding="utf-8",
    )

    health = cdx.load_health(cache_path)

    assert health == {
        "rafa": cdx.AccountSnapshot(
            status=cdx.HealthStatus.OK,
            primary_used_pct=12,
            secondary_used_pct=34,
            primary_reset_at=1782907200.0,
            secondary_reset_at=1783382400.0,
        )
    }


def test_load_health_preserves_compatibility_with_old_cache_shape(tmp_path: Path) -> None:
    cache_path = tmp_path / "health_cache.json"
    cache_path.write_text(
        json.dumps(
            {
                "rafa": {
                    "status": "ok",
                    "primary_used_pct": 12,
                    "secondary_used_pct": 34,
                }
            }
        ),
        encoding="utf-8",
    )

    health = cdx.load_health(cache_path)

    assert health == {
        "rafa": cdx.AccountSnapshot(
            status=cdx.HealthStatus.OK,
            primary_used_pct=12,
            secondary_used_pct=34,
            primary_reset_at=None,
            secondary_reset_at=None,
        )
    }


def test_main_status_prints_live_limits_for_selected_default(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    (base_dir / ".local/state/overdeck/systray/runtime" / "default_slug").write_text("avi\n", encoding="utf-8")
    write_health(
        base_dir,
        {
            "avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
    )

    fetch_calls: list[Path] = []

    class FakeHealthClient:
        def fetch(self, codex_home: Path, timeout_secs: float = 10.0) -> AccountSnapshot:
            fetch_calls.append(codex_home)
            return AccountSnapshot(
                HealthStatus.OK,
                10,
                20,
                primary_reset_at=1710003600.0,
                secondary_reset_at=1710604800.0,
            )

    monkeypatch.setattr(command_router, "AccountHealthClient", lambda: FakeHealthClient())
    monkeypatch.setattr(command_router.time, "time", lambda: 1710000000.0)

    exit_code = cdx.main(["cdx", "--status"])
    captured = capsys.readouterr()

    assert exit_code == 0
    assert fetch_calls == [base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "avi" / "CODEX_HOME"]
    assert captured.err == ""
    assert captured.out == "avi: 5h: 10% (1h left), 7d: 20% (7d left)\n"


def test_main_status_returns_one_when_live_limits_are_unavailable(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    write_health(
        base_dir,
        {
            "rafa": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
    )

    class FakeHealthClient:
        def fetch(self, codex_home: Path, timeout_secs: float = 10.0) -> AccountSnapshot:
            return AccountSnapshot(HealthStatus.UNKNOWN, None, None)

    monkeypatch.setattr(command_router, "AccountHealthClient", lambda: FakeHealthClient())

    exit_code = cdx.main(["cdx", "--usage"])
    captured = capsys.readouterr()

    assert exit_code == 1
    assert captured.out == ""
    assert captured.err.strip() == "cdx: live usage unavailable for rafa"


def test_main_usage_json_emits_structured_live_limits(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    (base_dir / ".local/state/overdeck/systray/runtime" / "default_slug").write_text("avi\n", encoding="utf-8")

    class FakeHealthClient:
        def fetch(self, codex_home: Path, timeout_secs: float = 10.0) -> AccountSnapshot:
            assert codex_home == base_dir / ".local/state/overdeck/systray/runtime" / "accounts" / "avi" / "CODEX_HOME"
            return AccountSnapshot(
                HealthStatus.OK,
                10,
                20,
                primary_reset_at=1710003600.0,
                secondary_reset_at=1710604800.0,
                checked_at=1710000000.0,
            )

    monkeypatch.setattr(command_router, "AccountHealthClient", lambda: FakeHealthClient())

    exit_code = cdx.main(["cdx", "--usage", "--json"])
    captured = capsys.readouterr()

    assert exit_code == 0
    assert captured.err == ""
    assert json.loads(captured.out) == {
        "schema_version": 1,
        "account": "avi",
        "checked_at": 1710000000.0,
        "status": "ok",
        "detail": None,
        "windows": {
            "five_hour": {"used_percentage": 10, "resets_at": 1710003600.0},
            "seven_day": {"used_percentage": 20, "resets_at": 1710604800.0},
        },
    }


def test_main_usage_json_emits_provider_state_when_limits_are_unavailable(
    base_dir: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    class FakeHealthClient:
        def fetch(self, codex_home: Path, timeout_secs: float = 10.0) -> AccountSnapshot:
            return AccountSnapshot(HealthStatus.UNKNOWN, None, None)

    monkeypatch.setattr(command_router, "AccountHealthClient", lambda: FakeHealthClient())

    exit_code = cdx.main(["cdx", "--usage", "--json"])
    captured = capsys.readouterr()

    assert exit_code == 1
    assert captured.err == ""
    assert json.loads(captured.out)["status"] == "unknown"
    assert json.loads(captured.out)["detail"] == "unknown"


def test_headless_guard_is_skipped_inside_a_sandbox_container(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    monkeypatch.setattr(cdx.remote_dispatch, "in_container", lambda: True)
    monkeypatch.setattr(cdx.Path, "home", lambda: tmp_path)

    def unreachable(*args: object, **kwargs: object) -> None:
        raise AssertionError("the guard was consulted inside a container")

    monkeypatch.setattr(cdx.subprocess, "run", unreachable)
    monkeypatch.setattr(cdx.os, "isatty", unreachable)

    assert cdx._deny_headless_local_dispatch() is None


def test_headless_guard_denies_dispatch_on_the_workstation(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    guard = tmp_path / ".claude" / "bin" / "local-dispatch-guard"
    guard.parent.mkdir(parents=True)
    guard.write_text("#!/usr/bin/bash\nexit 97\n", encoding="utf-8")
    guard.chmod(0o755)
    monkeypatch.setattr(cdx.remote_dispatch, "in_container", lambda: False)
    monkeypatch.setattr(cdx.Path, "home", lambda: tmp_path)

    with pytest.raises(SystemExit) as excinfo:
        cdx._deny_headless_local_dispatch()

    assert excinfo.value.code == 97
