"""
Module: src.export.json_exporter
Workorder: WO01
Purpose: JSON transcript export writer with schema-level validation.

Dependencies:
    - json: JSON serialization
    - pathlib: File path handling
    - typing: Type annotations

Inputs:
    - payload: Export data
    - target_path: Output file path

Outputs:
    - JSON export file on disk

Key Functions/Classes:
    - export_json: Writes JSON export file

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

from pydantic import ValidationError

from src.shared.errors import ProcessingError
from src.shared.models import TranscriptExport


def export_json(payload: dict[str, Any], target_path: Path) -> None:
    """Export validated transcript payload as JSON.

    Args:
        payload: Export payload.
        target_path: Output path.

    Raises:
        ProcessingError: If payload validation or write operation fails.
    """
    try:
        validated_payload = TranscriptExport.model_validate(payload)
    except ValidationError as error:
        raise ProcessingError(f"Invalid export payload: {error}") from error

    target_path.parent.mkdir(parents=True, exist_ok=True)
    with target_path.open("w", encoding="utf-8") as file:
        json.dump(validated_payload.model_dump(), file, ensure_ascii=False, indent=2)


def add_ollama_output_to_export(
    export_path: Path,
    model: str,
    host: str,
    text: str,
    summary: str | None = None,
    action_items: list[str] | None = None,
    title: str | None = None,
    topic: str | None = None,
    speakers: list[str] | None = None,
    outcomes: list[str] | None = None,
) -> None:
    """Add optional Ollama output section to an existing export JSON file.

    Args:
        export_path: Existing export JSON path.
        model: Ollama model name.
        host: Ollama host URL.
        text: Generated output text.
        summary: Optional concise summary.
        action_items: Optional list of action items.
        title: Optional generated title.
        topic: Optional generated topic.
        speakers: Optional speaker list.
        outcomes: Optional outcome list.

    Raises:
        ProcessingError: If file cannot be read/validated/written.
    """
    if not export_path.exists():
        raise ProcessingError(f"Export JSON not found: {export_path}")

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

    if not isinstance(payload, dict):
        raise ProcessingError("Export payload must be a JSON object.")

    payload["ollama_output"] = {
        "model": model,
        "host": host,
        "text": text,
        "summary": summary,
        "action_items": action_items or [],
        "title": title,
        "topic": topic,
        "speakers": speakers or [],
        "outcomes": outcomes or [],
    }

    export_json(payload, export_path)
