<?php

namespace App\Command;

use App\Service\AI\GeminiClient;
use App\Service\System\GitClient;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsCommand(
    name: 'app:git-log-update',
    description: 'Archive le dernier commit avec reformulation IA et notification Discord.',
)]
class GitSyncLogCommand extends Command
{
    private string $projectDir;

    public function __construct(
        private readonly HttpClientInterface $httpClient,
        KernelInterface $kernel,
        private readonly GitClient $gitClient,
        private readonly GeminiClient $geminiClient
    ) {
        parent::__construct();
        $this->projectDir = $kernel->getProjectDir();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        // Chemins dynamiques basés sur ProjectDir
        $filePath = $this->projectDir . '/var/update.json';
        $discordWebhook = 'https://discord.com/api/webhooks/1447983279902031963/O6P5oHVHFe2t2MgjFmOW-tOVrvdLf3JQDPAj8snlgKIrfGc8uJQKAHgqRJJjyoSsFYCR';

        // 1. Récupération des infos Git
        try {
            $gitInfo = $this->gitClient->getLastCommitInfo($this->projectDir);
        } catch (\RuntimeException $e) {
            $io->error("Erreur Git : " . $e->getMessage());
            return Command::FAILURE;
        }

        $rawMessage = $gitInfo['message'];
        $commitDate = $gitInfo['date'];
        $commitHash = $gitInfo['hash'];

        // 2. Détermination du TYPE (feature, fix, optimise, new)
        $type = 'new';
        $lowerMsg = strtolower($rawMessage);
        if (preg_match('/(fix|bug|patch|correct)/', $lowerMsg)) $type = 'fix';
        elseif (preg_match('/(feat|add|create|nouveau|new)/', $lowerMsg)) $type = 'feature';
        elseif (preg_match('/(perf|opti|refactor|clean|speed)/', $lowerMsg)) $type = 'optimise';

        // 3. Vérification anti-doublon
        $data = [];
        if (file_exists($filePath)) {
            $data = json_decode(file_get_contents($filePath), true) ?? [];
        }

        if (!empty($data) && $data[0]['hash'] === $commitHash) {
            $io->info("Le commit [$commitHash] est déjà à jour.");
            return Command::SUCCESS;
        }

        // 4. Appel IA Gemini
        $friendlyMessage = $rawMessage;
        $aiMessage = $this->geminiClient->generateFriendlyMessage($rawMessage);
        if ($aiMessage) {
            $friendlyMessage = $aiMessage;
        } else {
            $io->warning("L'IA n'a pas pu traiter le message.");
        }

        // 5. Mise à jour du fichier JSON
        $newEntry = [
            'type'    => $type,
            'message' => $friendlyMessage,
            'date'    => $commitDate,
            'hash'    => $commitHash
        ];

        array_unshift($data, $newEntry);
        $data = array_slice($data, 0, 6);

        $varDir = $this->projectDir . '/var';
        if (!is_dir($varDir)) {
            mkdir($varDir, 0777, true);
        }

        file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        // 6. Envoi Discord
        try {
            $icons = [
                'feature'  => '🚀 **Nouveauté**',
                'fix'      => '🛠️ **Correction**',
                'optimise' => '⚡ **Optimisation**',
                'new'      => '✨ **Mise à jour**',
            ];

            $selectedIcon = $icons[$type] ?? $icons['new'];

            $discordMessage = sprintf(
                "%s\n📢 *Mise à jour en cours de mise en ligne sur votre intranet*\n\n> %s",
                $selectedIcon,
                $friendlyMessage
            );
            $this->httpClient->request('POST', $discordWebhook, [
                'json' => ['content' => $discordMessage]
            ]);
            $io->note("Notification Discord envoyée.");
        } catch (\Exception $e) {
            $io->error("Erreur Discord : " . $e->getMessage());
        }

        $io->success("Journal client mis à jour avec succès.");
        return Command::SUCCESS;
    }
}
