<?php
// src/Knowledge/Ingest/DocumentLoader.php

declare(strict_types=1);

namespace App\Knowledge\Ingest;

use Smalot\PdfParser\Parser;

final class DocumentLoader
{
    public function load(string $path): string
    {
        if (!is_file($path)) {
            throw new \RuntimeException("File not found: {$path}");
        }

        $ext = mb_strtolower(pathinfo($path, PATHINFO_EXTENSION));

        return match ($ext) {
            'txt', 'md' => $this->loadText($path),
            'pdf'       => $this->loadPdf($path),
            default     => throw new \RuntimeException("Unsupported file type: .{$ext}"),
        };
    }

    private function loadText(string $path): string
    {
        $content = file_get_contents($path);

        if ($content === false) {
            throw new \RuntimeException("Could not read file: {$path}");
        }

        return $this->normalizeLineEndings($content);
    }

    private function loadPdf(string $path): string
    {
        $parser = new Parser();

        try {
            $pdf  = $parser->parseFile($path);
            $text = $pdf->getText();
        } catch (\Throwable $e) {
            throw new \RuntimeException(
                "Failed to parse PDF: {$path}. Error: " . $e->getMessage(),
                0,
                $e
            );
        }

        return $this->normalizeLineEndings($text);
    }

    /**
     * Loader ist bewusst minimal.
     *
     * KEINE:
     * - Silbentrennung
     * - Listen-Reparatur
     * - Struktur-Merges
     * - Regex-Orgie
     *
     * Nur:
     * - Zeilenumbrüche vereinheitlichen
     * - trim
     */
    private function normalizeLineEndings(string $text): string
    {
        if ($text === '') {
            return '';
        }

        // Einheitliche Zeilenumbrüche
        $text = str_replace(["\r\n", "\r"], "\n", $text);

        return trim($text);
    }
}