<?php

declare(strict_types=1);

namespace App\Eval;

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

    /**
     * @param array<string, mixed> $report
     */
    public function write(array $report, string $filename = 'last-run.json'): string
    {
        $directory = sprintf('%s/tests/evals/reports', $this->projectDir);

        if (!is_dir($directory) && !mkdir($directory, 0775, true) && !is_dir($directory)) {
            throw new \RuntimeException(sprintf(
                'Failed to create eval report directory: %s',
                $directory
            ));
        }

        $path = sprintf('%s/%s', $directory, ltrim($filename, '/'));

        $json = json_encode(
            $report,
            JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        );

        if (!is_string($json)) {
            throw new \RuntimeException('json_encode failed for eval report.');
        }

        $tmpPath = $path . '.tmp';

        if (file_put_contents($tmpPath, $json) === false) {
            throw new \RuntimeException(sprintf(
                'Failed to write temporary eval report file: %s',
                $tmpPath
            ));
        }

        if (!rename($tmpPath, $path)) {
            @unlink($tmpPath);

            throw new \RuntimeException(sprintf(
                'Failed to move temporary eval report into place: %s',
                $path
            ));
        }

        return $path;
    }
}