"""Prompt loader module for language-specific optimization prompts.

This module provides a unified interface to load prompts based on language.
Each language stores its optimizer prompts in its own module directory.
"""

from __future__ import annotations

from pathlib import Path

_LANGUAGES_DIR = Path(__file__).parent.parent.parent.parent  # core/languages/

_LANGUAGE_PROMPT_DIRS: dict[str, Path] = {
    "python": _LANGUAGES_DIR / "python" / "optimizer" / "prompts" / "python",
    "javascript": _LANGUAGES_DIR / "js_ts" / "prompts" / "optimizer",
    "java": _LANGUAGES_DIR / "java" / "prompts" / "optimizer",
}
# TypeScript reuses the JavaScript prompts
_LANGUAGE_PROMPT_DIRS["typescript"] = _LANGUAGE_PROMPT_DIRS["javascript"]


def _get_prompt_dir(language: str) -> Path:
    prompt_dir = _LANGUAGE_PROMPT_DIRS.get(language)
    if prompt_dir is None or not prompt_dir.exists():
        msg = f"No prompts found for language: {language}"
        raise ValueError(msg)
    return prompt_dir


def get_system_prompt(language: str, is_async: bool = False) -> str:  # noqa: FBT001, FBT002
    """Load the system prompt for the given language."""
    variant = "async_system_prompt.md" if is_async else "system_prompt.md"
    prompt_file = _get_prompt_dir(language) / variant

    if not prompt_file.exists():
        msg = f"No system prompt found for language: {language}"
        raise ValueError(msg)

    return prompt_file.read_text()


def get_user_prompt(language: str, is_async: bool = False) -> str:  # noqa: FBT001, FBT002
    """Load the user prompt for the given language."""
    variant = "async_user_prompt.md" if is_async else "user_prompt.md"
    prompt_file = _get_prompt_dir(language) / variant

    if not prompt_file.exists():
        msg = f"No user prompt found for language: {language}"
        raise ValueError(msg)

    return prompt_file.read_text()


def get_available_languages() -> list[str]:
    """Get a list of languages that have prompts available."""
    return sorted(lang for lang, path in _LANGUAGE_PROMPT_DIRS.items() if lang != "typescript" and path.exists())
