from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest

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

import account_lock_cli
from account_registry import AccountRegistry, AccountRegistryKind


def _registry(tmp_path: Path) -> AccountRegistry:
    registry = AccountRegistry(
        base_dir=tmp_path / "runtime",
        legacy_codex_home=tmp_path / ".codex",
        kind=AccountRegistryKind.CODEX,
    )
    account_home = registry.add_dir("owner", "Owner")
    (account_home / "auth.json").write_text("{}", encoding="utf-8")
    registry.set_default(registry.list()[0])
    return registry


def test_cli_lock_status_and_unlock_require_human_confirmation(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    registry = _registry(tmp_path)
    monkeypatch.setattr(
        account_lock_cli,
        "_registry",
        lambda _base_dir, tool: registry
        if tool == "codex"
        else pytest.fail(f"unexpected tool: {tool}"),
    )
    confirmations: list[tuple[str, str, str]] = []
    monkeypatch.setattr(
        account_lock_cli,
        "confirm_human_action",
        lambda action, tool, slug: confirmations.append((action, tool, slug)),
    )
    base_args = ["--base-dir", str(registry.base_dir)]

    assert account_lock_cli.run([*base_args, "lock", "codex", "Owner"]) == 0
    assert registry.is_locked("owner") is True
    assert confirmations == [("lock", "codex", "owner")]
    assert "codex:owner is now locked" in capsys.readouterr().out

    assert (
        account_lock_cli.run(
            [*base_args, "--json", "status", "codex", "owner"]
        )
        == 0
    )
    payload = json.loads(capsys.readouterr().out)
    assert payload == {
        "accounts": [
            {
                "tool": "codex",
                "slug": "owner",
                "alias": "Owner",
                "locked": True,
                "default": True,
            }
        ]
    }

    assert account_lock_cli.run([*base_args, "unlock", "codex", "owner"]) == 0
    assert registry.is_locked("owner") is False
    assert confirmations[-1] == ("unlock", "codex", "owner")
    capsys.readouterr()

    assert account_lock_cli.run([*base_args, "unlock", "codex", "owner"]) == 0
    assert confirmations == [
        ("lock", "codex", "owner"),
        ("unlock", "codex", "owner"),
    ]
    assert "already unlocked" in capsys.readouterr().out
