from __future__ import annotations

import json
import sys
from pathlib import Path
from types import SimpleNamespace

import pytest

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

import gateway_account_cli as cli
from account_registry import AccountRef


class FakeAccount:
    tool = "codex"
    slug = "fixture"
    authority_binding = None


class FakeRegistry:
    def list(self):
        return [FakeAccount()]


class FakeManager:
    def __init__(self, _registry) -> None:
        self.calls: list[str] = []
        self._current = FakeAccount()

    def stage(self, _account):
        self.calls.append("stage")
        return SimpleNamespace(as_dict=lambda: {"state": "dark"})

    def current(self, _slug: str):
        self.calls.append("current")
        return self._current

    def activate(self, _account):
        self.calls.append("activate")
        return SimpleNamespace(as_dict=lambda: {"state": "authority"})

    def cancel(self, _account):
        self.calls.append("cancel")
        return SimpleNamespace(as_dict=lambda: {"state": "native-cancelled"})


def test_migrate_stages_then_activates(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
    manager = FakeManager(FakeRegistry())
    monkeypatch.setattr(cli, "_registry", lambda _tool: FakeRegistry())
    monkeypatch.setattr(cli, "LocalGatewayAccountManager", lambda _registry: manager)

    assert cli.main(["migrate", "--tool", "codex", "--account", "fixture"]) == 0
    assert manager.calls == ["stage", "current", "activate"]
    assert json.loads(capsys.readouterr().out)["state"] == "authority"


def test_status_does_not_mutate(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
    monkeypatch.setattr(cli, "_registry", lambda _tool: FakeRegistry())
    monkeypatch.setattr(cli, "gateway_account_state", lambda _account: SimpleNamespace(value="native"))

    assert cli.main(["status", "--tool", "codex", "--account", "fixture"]) == 0
    assert json.loads(capsys.readouterr().out) == {
        "tool": "codex",
        "account": "fixture",
        "state": "native",
    }
