"""Application layer tests for configuration services."""

import json
from pathlib import Path
from typing import Any

import pytest

from aitop.application.configuration import (
    ConfigSource,
    load_process_patterns,
    load_themes,
)


class _PayloadSource(ConfigSource):
    def __init__(self, payload: Any) -> None:
        self._payload = payload

    def load_json(self, file_path: Path) -> Any:
        del file_path
        return self._payload


class _NotFoundSource(ConfigSource):
    def load_json(self, file_path: Path) -> Any:
        del file_path
        raise FileNotFoundError("missing")


class _BadJSONSource(ConfigSource):
    def load_json(self, file_path: Path) -> Any:
        del file_path
        raise json.JSONDecodeError("bad", "{", 1)


def test_load_process_patterns_accepts_valid_payload() -> None:
    patterns = load_process_patterns(
        Path("/tmp/patterns.json"),
        source=_PayloadSource([r"torchrun", r"vllm"]),
    )

    assert patterns == [r"torchrun", r"vllm"]


def test_load_process_patterns_rejects_invalid_payload() -> None:
    with pytest.raises(
        RuntimeError,
        match="Process patterns file must contain a list of strings",
    ):
        load_process_patterns(Path("/tmp/patterns.json"), source=_PayloadSource([1, 2]))


def test_load_themes_rejects_missing_themes_key() -> None:
    with pytest.raises(RuntimeError, match="Missing 'themes' key in theme file"):
        load_themes(Path("/tmp/themes.json"), source=_PayloadSource({"palette": {}}))


def test_load_themes_wraps_file_not_found() -> None:
    with pytest.raises(RuntimeError, match="Failed to load themes from"):
        load_themes(Path("/tmp/missing.json"), source=_NotFoundSource())


def test_load_themes_wraps_json_decode_errors() -> None:
    with pytest.raises(RuntimeError, match="Failed to load themes from"):
        load_themes(Path("/tmp/themes.json"), source=_BadJSONSource())
