"""
Module: src.transcription.prompt_builder
Workorder: WO01
Purpose: Build Whisper initial prompt from local vocabulary terms.

Dependencies:
    - pathlib: File path handling
    - json: Parse terms file

Inputs:
    - terms_path: Path to local terms.json

Outputs:
    - Prompt string for vocabulary boosting

Key Functions/Classes:
    - build_initial_prompt: Creates prompt from domain terms

Tests: tests/unit/test_placeholder.py
"""
from pathlib import Path
import json

from src.shared.errors import ProcessingError


def build_initial_prompt(terms_path: Path) -> str:
    """Build initial prompt from `terms.json`.

    Args:
        terms_path: Path to terms file.

    Returns:
        Prompt text containing domain vocabulary.

    Raises:
        ProcessingError: If the terms file is missing or malformed.
    """
    if not terms_path.exists():
        raise ProcessingError(f"Terms file not found: {terms_path}")

    try:
        with terms_path.open("r", encoding="utf-8") as file:
            terms = json.load(file)
    except json.JSONDecodeError as error:
        raise ProcessingError(f"Invalid JSON in terms file: {terms_path}") from error

    if not isinstance(terms, list):
        raise ProcessingError("terms.json must be a JSON array of strings.")

    cleaned_terms = [term.strip() for term in terms if isinstance(term, str) and term.strip()]
    if not cleaned_terms:
        return ""

    return "Beachte insbesondere folgende Begriffe: " + ", ".join(cleaned_terms)
