"""Load, validate, and serve the 54-text evaluation corpus."""

from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional

import jsonschema


@dataclass
class TestText:
    id: str
    domain: str
    difficulty: str
    text: str
    source: str
    ground_truth: Dict[str, Any]


def load_corpus(corpus_path: Optional[Path] = None) -> List[TestText]:
    """Load and validate the corpus against schema."""
    corpus_path = corpus_path or Path(__file__).parent / "texts.json"
    schema_path = Path(__file__).parent / "schema.json"

    with open(corpus_path, encoding="utf-8") as f:
        data = json.load(f)
    with open(schema_path, encoding="utf-8") as f:
        schema = json.load(f)

    jsonschema.validate(data, schema)
    return [TestText(**t) for t in data["texts"]]


def filter_corpus(
    texts: List[TestText],
    domain: Optional[str] = None,
    difficulty: Optional[str] = None,
) -> List[TestText]:
    """Filter corpus by domain and/or difficulty."""
    result = texts
    if domain:
        result = [t for t in result if t.domain == domain]
    if difficulty:
        result = [t for t in result if t.difficulty == difficulty]
    return result
