"""Tests for prodigy_teams.commands._state — CLI context and state management."""

from __future__ import annotations

from pathlib import Path

import pytest

from prodigy_teams.commands._state import (
    clear_state,
    cli_context,
    get_root_cfg,
    get_saved_settings,
    get_secrets,
)
from prodigy_teams.config import SavedSettings


class TestCliContext:
    def test_provides_root_cfg(self, tmp_path: Path):
        with cli_context(config_dir=tmp_path):
            cfg = get_root_cfg()
            assert cfg.config_dir == tmp_path

    def test_clears_after_exit(self, tmp_path: Path):
        with cli_context(config_dir=tmp_path):
            pass
        # The conftest autouse fixture sets its own context, so after our
        # context exits the outer conftest context is still active.
        # Instead, verify that we get the conftest context, not ours.
        cfg = get_root_cfg()
        assert cfg.config_dir != tmp_path

    def test_with_saved_settings(self, tmp_path: Path):
        settings = SavedSettings(pam_host="test.host")
        with cli_context(config_dir=tmp_path, saved_settings=settings):
            s = get_saved_settings()
            assert s.pam_host == "test.host"

    def test_get_saved_settings_from_file(self, tmp_path: Path):
        with cli_context(config_dir=tmp_path):
            s = get_saved_settings()
            assert s.broker_host is None  # Blank defaults

    def test_get_secrets_from_file(self, tmp_path: Path):
        with cli_context(config_dir=tmp_path):
            s = get_secrets()
            assert s.id_token is None


class TestClearState:
    def test_clears_all(self, tmp_path: Path):
        with cli_context(config_dir=tmp_path):
            get_root_cfg()  # Ensure it's set
            clear_state()
            with pytest.raises(RuntimeError):
                get_root_cfg()


class TestGetRootCfg:
    def test_raises_without_context(self):
        clear_state()
        with pytest.raises(RuntimeError, match="No CLI context set"):
            get_root_cfg()
