import json
from pathlib import Path

import pytest

from aitop.config import load_process_patterns, load_themes


def _write_json(path: Path, payload: object) -> Path:
    path.write_text(json.dumps(payload), encoding="utf-8")
    return path


def test_load_process_patterns_accepts_valid_string_list(tmp_path: Path) -> None:
    patterns_file = _write_json(
        tmp_path / "patterns.json",
        [r"python.*train", r"vllm", r"torchrun"],
    )

    patterns = load_process_patterns(patterns_file)

    assert patterns == [r"python.*train", r"vllm", r"torchrun"]


def test_load_process_patterns_rejects_non_string_entries(tmp_path: Path) -> None:
    patterns_file = _write_json(tmp_path / "patterns.json", [r"python", 7, {"x": 1}])

    with pytest.raises(
        RuntimeError,
        match="Process patterns file must contain a list of strings",
    ):
        load_process_patterns(patterns_file)


def test_load_themes_rejects_missing_themes_key(tmp_path: Path) -> None:
    theme_file = _write_json(tmp_path / "themes.json", {"palette": {}})

    with pytest.raises(RuntimeError, match="Missing 'themes' key in theme file"):
        load_themes(theme_file)


def test_load_themes_rejects_non_mapping_themes(tmp_path: Path) -> None:
    theme_file = _write_json(tmp_path / "themes.json", {"themes": ["default"]})

    with pytest.raises(RuntimeError, match="'themes' must be a dictionary"):
        load_themes(theme_file)


def test_load_themes_rejects_missing_default_theme(tmp_path: Path) -> None:
    theme_file = _write_json(
        tmp_path / "themes.json",
        {"themes": {"dark": {"colors": {}}}},
    )

    with pytest.raises(RuntimeError, match="Missing required 'default' theme"):
        load_themes(theme_file)
