<?php

declare(strict_types=1);

namespace App\Service\Admin;

use App\Entity\ModelGenerationConfig;
use App\Knowledge\Retrieval\NdjsonHybridRetriever;
use App\Repository\ModelGenerationConfigRepository;
use App\Service\ModelGenerationConfigManager;
use Doctrine\ORM\EntityManagerInterface;

final class ModelGenerationConfigAdminService
{
    public function __construct(
        private readonly ModelGenerationConfigRepository $repository,
        private readonly EntityManagerInterface $em,
        private readonly ModelGenerationConfigManager $manager,
        private readonly NdjsonHybridRetriever $retriever,
    ) {}

    public function list(): array
    {
        return $this->repository->findBy(
            [],
            ['active' => 'DESC', 'modelName' => 'ASC', 'version' => 'DESC']
        );
    }

    public function create(array $data): ModelGenerationConfig
    {
        $modelName = $this->requireString($data['model_name'] ?? null, 'model_name');

        $version = $this->repository->findNextVersion($modelName);

        $config = new ModelGenerationConfig(
            modelName: $modelName,
            version: $version,
            stream: (bool)($data['stream'] ?? false),
            temperature: (float)($data['temperature'] ?? 0.7),
            topK: (int)($data['top_k'] ?? 40),
            topP: (float)($data['top_p'] ?? 0.9),
            repeatPenalty: (float)($data['repeat_penalty'] ?? 1.1),
            numCtx: (int)($data['num_ctx'] ?? 4096),
            active: false,
            retrievalMaxChunks: (int)($data['retrieval_max_chunks'] ?? 25),
            retrievalVectorTopK: (int)($data['retrieval_vector_top_k'] ?? 25),
        );

        $this->em->persist($config);
        $this->em->flush();

        return $config;
    }

    public function activate(ModelGenerationConfig $config): void
    {
        $this->manager->activate($config);
    }

    public function delete(ModelGenerationConfig $config): void
    {
        if ($config->isActive()) {
            throw new \RuntimeException('Aktive Konfiguration kann nicht gelöscht werden.');
        }

        $this->em->remove($config);
        $this->em->flush();
    }

    public function testRetrieval(ModelGenerationConfig $config, string $prompt): array
    {
        if (trim($prompt) === '') {
            return [];
        }

        return $this->retriever->retrieveDebug($prompt,$config);
    }

    private function requireString(mixed $value, string $field): string
    {
        if (!is_string($value) || trim($value) === '') {
            throw new \InvalidArgumentException("Invalid value for {$field}");
        }
        return trim($value);
    }
}