<?php

declare(strict_types=1);

namespace App\Eval;

use App\Eval\Dto\EvalCase;

final readonly class EvalCaseLoader
{
    public function __construct(
        private string $projectDir,
    ) {
    }

    /**
     * @return array<int, EvalCase>
     */
    public function load(string $type = 'retrieval'): array
    {
        $path = sprintf(
            '%s/tests/evals/cases/%s.ndjson',
            $this->projectDir,
            $type
        );

        if (!is_file($path)) {
            throw new \RuntimeException(sprintf(
                'Eval case file not found: %s',
                $path
            ));
        }

        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        if ($lines === false) {
            throw new \RuntimeException(sprintf(
                'Failed to read eval case file: %s',
                $path
            ));
        }

        $cases = [];

        foreach ($lines as $lineNumber => $line) {
            $line = trim($line);

            if ($line === '') {
                continue;
            }

            $decoded = json_decode($line, true);

            if (!is_array($decoded)) {
                throw new \RuntimeException(sprintf(
                    'Invalid JSON in %s on line %d.',
                    $path,
                    $lineNumber + 1
                ));
            }

            $cases[] = EvalCase::fromArray($decoded);
        }

        return $cases;
    }
}