"""Load coding tasks from JSON files."""

from __future__ import annotations

import json
from pathlib import Path

from cohort.benchmark.config import CodingTask, TestCase


def load_task(path: Path) -> CodingTask:
    """Load a single task from a JSON file."""
    data = json.loads(path.read_text(encoding="utf-8"))
    test_cases = [
        TestCase(
            input=tc["input"],
            expected_output=tc["expected_output"],
            is_sample=tc.get("is_sample", True),
        )
        for tc in data.get("test_cases", [])
    ]
    return CodingTask(
        task_id=data["task_id"],
        title=data["title"],
        description=data["description"],
        input_format=data.get("input_format", ""),
        output_format=data.get("output_format", ""),
        constraints=data.get("constraints", ""),
        test_cases=test_cases,
        time_limit_seconds=data.get("time_limit_seconds", 5.0),
        difficulty=data.get("difficulty", "medium"),
        tags=data.get("tags", []),
    )


def load_all_tasks(directory: Path) -> list[CodingTask]:
    """Load all tasks from a directory of JSON files."""
    tasks = []
    for path in sorted(directory.glob("*.json")):
        tasks.append(load_task(path))
    return tasks
