#!/usr/bin/env python3
"""Application-level configuration loading services."""

import json
import logging
from pathlib import Path
from typing import Any, Optional, Protocol

from ..domain.config_validation import (
    ThemeMap,
    validate_process_patterns,
    validate_themes_payload,
)


class ConfigSource(Protocol):
    """Protocol for reading raw configuration payloads."""

    def load_json(self, file_path: Path) -> Any:
        """Load and return parsed JSON payload for the given path."""


def _default_process_patterns_path() -> Path:
    return (
        Path(__file__).resolve().parent.parent / "config" / "ai_process_patterns.json"
    )


def _default_themes_path() -> Path:
    return Path(__file__).resolve().parent.parent / "config" / "themes.json"


def load_process_patterns(
    patterns_file: Optional[Path] = None,
    source: Optional[ConfigSource] = None,
) -> list[str]:
    """Load AI process patterns from configuration."""
    if patterns_file is None:
        patterns_file = _default_process_patterns_path()
        logging.debug(f"Using default process patterns file: {patterns_file}")
    else:
        logging.debug(f"Using custom process patterns file: {patterns_file}")

    if source is None:
        raise RuntimeError("ConfigSource is required for load_process_patterns")
    try:
        payload = source.load_json(patterns_file)
        patterns = validate_process_patterns(payload)
        logging.debug(f"Loaded {len(patterns)} process patterns")
        return patterns
    except (FileNotFoundError, json.JSONDecodeError, ValueError) as exc:
        raise RuntimeError(
            f"Failed to load process patterns from {patterns_file}: {str(exc)}"
        )


def load_themes(
    theme_file: Optional[Path] = None,
    source: Optional[ConfigSource] = None,
) -> ThemeMap:
    """Load theme configuration mapping."""
    if theme_file is None:
        theme_file = _default_themes_path()
        logging.debug(f"Using default theme file: {theme_file}")
    else:
        logging.debug(f"Using custom theme file: {theme_file}")

    if source is None:
        raise RuntimeError("ConfigSource is required for load_themes")
    try:
        payload = source.load_json(theme_file)
        logging.debug("Theme file loaded successfully")
        themes = validate_themes_payload(payload)
        logging.debug(f"Loaded {len(themes)} themes")
        return themes
    except (FileNotFoundError, json.JSONDecodeError) as exc:
        raise RuntimeError(f"Failed to load themes from {theme_file}: {str(exc)}")
    except (KeyError, ValueError) as exc:
        raise RuntimeError(f"Invalid theme configuration in {theme_file}: {str(exc)}")


__all__ = ["ConfigSource", "load_process_patterns", "load_themes"]
