<?php

declare(strict_types=1);

namespace App\Application\Website;

use App\Application\Service\QrCodeService;
use App\Domain\AI\AiModel;
use App\Domain\Media\ImageRepository;
use App\Domain\Media\ImageSlot;
use App\Framework\Attributes\Route;
use App\Framework\Cache\Cache;
use App\Framework\Core\PathProvider;
use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\EntityManager;
use App\Framework\DateTime\Clock;
use App\Framework\DateTime\DateTimeFormatter;
use App\Framework\DI\DefaultContainer;
use App\Framework\Http\Method;
use App\Framework\Http\Request;
use App\Framework\Http\Session\SessionInterface;
use App\Framework\HttpClient\CurlHttpClient;
use App\Framework\Markdown\MarkdownConverter;
use App\Framework\Meta\MetaData;
use App\Framework\Meta\StaticPageMetaResolver;
use App\Framework\QueryBus\QueryBus;
use App\Framework\Router\Result\ViewResult;
use App\Framework\Router\UrlGenerator;
use App\Framework\Router\WebRoutes;
use App\Framework\SyntaxHighlighter\FileHighlighter;
use App\Framework\SyntaxHighlighter\SyntaxHighlighter;
use App\Infrastructure\AI\AiHandlerFactory;
use App\Infrastructure\AI\AiService;
use App\Infrastructure\GeoIp\DatabaseSetup;
use App\Infrastructure\GeoIp\GeoIp;

final readonly class ShowHome
{
    public function __construct(
        private QueryBus            $queryBus,
        private DefaultContainer    $container,
        private Clock               $clock,
        private DateTimeFormatter   $dateTimeFormatter,
        private EntityManager       $entityManager,
        private Cache               $cache,
        private ConnectionInterface $connection,
        private PathProvider        $pathProvider,
        private UrlGenerator        $urlGenerator,
        private ImageRepository             $imageRepository,
    ) {
    }

    #[Route(path: '/', method: Method::GET, name: WebRoutes::HOME)]
    public function home(HomeRequest $request, string $test = 'hallo'): ViewResult
    {
        #$imageSlot = $this->entityManager->findOneBy(ImageSlot::class, ['slot_name' => 'slot1']);

        /*$image = $this->imageRepository->findBySlotName('slot1');



        $filepath = $image->filename;

        echo "<img src='/images/{$filepath}'  alt='AltText' style='width: 400px; object-fit: cover; aspect-ratio: 1; border-radius: 10px;'/>";*/


        $model = new HomeViewModel('Hallo Welt!');

        #$image = $this->imageRepository->findById("06BV7BSMPRX9ADY7XAQ5EC55YW");

        #$filepath = "images/" . $image->filename;

        #echo "<img src='{$filepath}'  alt='AltText'/>";

        /*var_dump(sys_getloadavg());

        # Beginn
        $cpu_count = 1;
        if(is_file('/proc/cpuinfo')) {
            $cpuinfo = file_get_contents('/proc/cpuinfo');
            preg_match_all('/^processor/m', $cpuinfo, $matches);
            $cpu_count = count($matches[0]);
        }

        $sys_getloadavg = sys_getloadavg();
        $sys_getloadavg[0] = $sys_getloadavg[0] / $cpu_count;
        $sys_getloadavg[1] = $sys_getloadavg[1] / $cpu_count;
        $sys_getloadavg[2] = $sys_getloadavg[2] / $cpu_count;

        var_dump("<pre>", $sys_getloadavg);

        $cpuinfo = file_get_contents('/proc/cpuinfo');

        #var_dump("<pre>", $cpuinfo);*/



        $highlighter = new SyntaxHighlighter();

        $code = '<?php

# Some Demo Function
 function test(string $value): string
 {
    $result = $value;
    return $result;
 }
 ?>';

        #$code = file_get_contents(__DIR__ . '/ShowHome.php');

        #echo new FileHighlighter()(__DIR__ . '/ShowHome.php', 48, 20);

        // Einmalige Initialisierung
        #$setup = new DatabaseSetup(__DIR__ . '/Infrastructure/GeoIp/data/ip_country.sqlite');
        #$setup->setupCompleteDatabase();

        // Normale Verwendung
        $geoIp = new GeoIp(__DIR__ . '/Infrastructure/GeoIp/data/ip_country.sqlite');
        $countryInfo = $geoIp->getCountryInfo('83.135.161.55');

        /*echo 'Code: ' . $countryInfo->countryCode . "\n";
        echo 'Deutsch: ' . $countryInfo->getGermanName() . "\n";
        echo 'English: ' . $countryInfo->getEnglishName() . "\n";

        var_dump($countryInfo);*/



        $model = new HomeViewModel('Hallo Welt!');

        $aiService = new AiService(new AiHandlerFactory(new CurlHttpClient()));




        /* $status = opcache_get_status(true);
         unset($status['scripts']);


         $response = $aiService->query('Bitte visualisiere mir den OPCache Status kompakt: '.print_r($status, true), AiModel::OLLAMA_QWEN2_5);

         $response = $aiService->query('Du wirst in meinem PHP Framework ausgeführt. Kann ich dir Frameworkdaten irgendwie zugänglich machen?', AiModel::OLLAMA_QWEN2_5, messages: [
             ['role' => 'system', 'content' => 'Du bist ein hilfreicher Programmier-Assistent.'],
             ['role' => 'user', 'content' => 'Du wirst in meinem PHP Framework ausgeführt. Kann ich dir Frameworkdaten irgendwie zugänglich machen?'],
             ['role' => 'user', 'content' => ''],
             ]);

         $html = new MarkdownConverter()->toHtml($response->content);

         echo $html;*/



        // Get session from container (available after SessionMiddleware runs)
        if ($this->container->has(SessionInterface::class)) {
            $session = $this->container->get(SessionInterface::class);

            if ($session->validation->has('form', 'consent')) {
                #debug($session->form->get('form'));
                #debug($session->validation->getField('form', 'consent'));
                // Only clear the specific form, not all forms
                $session->validation->clear('form');
                $session->form->clear('form');
            }
        }


        // Cache löschen für frische Ergebnisse
        #$this->cache->forget('unified_discovery_results');
        #$this->cache->forget('attribute_discovery');


        #var_dump("<pre>");

        // Debug-Ausgaben hinzufügen
        #var_dump('Discovery Results:' , $results->toArray());
        #var_dump('All Attribute Results:', $results->getAllAttributeResults());
        #var_dump('Processed File Count:', $discovery->getProcessedFileCount());

        // Teste ob ShowHome gefunden wird
        $basePath = $this->pathProvider->getBasePath();
        #debug('Scanning path:', $basePath . '/src');



        /*
         *  [Field] => id
            [Type] => int(11)
            [Null] => NO
            [Key] => PRI
            [Default] =>
            [Extra] =>
         */

        /*$tables = $this->connection->query('SHOW FULL TABLES;')->fetchAll();
        $columns = $this->connection->query('SHOW COLUMNS FROM users;')->fetchAll();
        $table = "<h2>Table: test</h2><table><tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th><th>Default</th></tr>";

        foreach ($columns as $column) {
            $table .= sprintf("<tr> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td></tr>", $column['Field'], $column['Type'], $column['Null'], $column['Key'], $column['Default']);
        }
        $table .= "</table>";

        echo $table;


        dd($columns);*/



        $result = $this->queryBus->dispatch(new DemoQuery());

        #echo $result->test;

        $httpRequest = $this->container->get(Request::class);

        $protocol = $httpRequest->server->getHttpHost();


        #debug($this->entityManager->find(User::class, 1)->name, 'User');

        #$qrCodeService = new QrCodeService(new QrCodeGenerator(new QrCodeEncoder(), new QrCodeRenderer()));

        #$code = $qrCodeService->generateQrCode('Michael Schiemer');

        #echo $code->toSvg();


        #var_dump($this->dateTimeFormatter->formatTime($this->clock->now()));


        return new ViewResult(
            template: 'test',
            metaData: new StaticPageMetaResolver(
                title: 'Home',
                description: 'Hallo Welt!',
            )(),
            data: ['name' => 'Michael'],
            model: $model,
        );
    }

    #[Route(path: '/epk', name: WebRoutes::EPK)]
    public function epk(string $test = 'hallo'): ViewResult
    {
        return new ViewResult(
            'test',
            new MetaData('EPK'),
        );
    }

    #[Route(path: '/designsystem')]
    public function designSystem(): ViewResult
    {
        return new ViewResult(
            'designsystem',
            new MetaData('DesignSystem')
        );
    }
}
