<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/admin/vector')]
final class AdminVectorLogController extends AbstractController
{
    #[Route('/log', name: 'admin_vector_log')]
    public function view(): Response
    {
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');

        // ⚠️ Pfad ggf. anpassen falls bei dir anders konfiguriert
        $logFile = \dirname(__DIR__, 3) . '/var/log/vector_service.log';

        if (!\file_exists($logFile)) {
            return $this->render('admin/vector/log.html.twig', [
                'content' => 'vector_service.log not found.',
                'fileExists' => false,
            ]);
        }

        $content = $this->readLastLines($logFile, 500);

        return $this->render('admin/vector/log.html.twig', [
            'content' => $content,
            'fileExists' => true,
        ]);
    }

    /**
     * Read last N lines safely (memory-friendly)
     */
    private function readLastLines(string $file, int $lines = 500): string
    {
        $handle = \fopen($file, 'rb');
        if (!$handle) {
            return 'Unable to open log file.';
        }

        $buffer = '';
        $chunkSize = 4096;
        $lineCount = 0;
        $pos = -1;

        \fseek($handle, 0, SEEK_END);
        $fileSize = \ftell($handle);

        while ($lineCount < $lines && -$pos < $fileSize) {
            $step = \min($chunkSize, $fileSize + $pos);
            \fseek($handle, $pos - $step, SEEK_END);
            $chunk = \fread($handle, $step);
            $buffer = $chunk . $buffer;
            $lineCount += \substr_count($chunk, "\n");
            $pos -= $step;
        }

        \fclose($handle);

        $linesArray = \explode("\n", $buffer);
        return \implode("\n", \array_slice($linesArray, -$lines));
    }
}