<?php
class Stats {
    private static $storiesDir = __DIR__ . '/../stories/';
    private $stories = [];
    private $stats = [];

    public function __construct() {
        $this->loadStories();
        $this->calculateStats();
    }

    private function loadStories() {
        foreach (glob(self::$storiesDir . '*.json') as $file) {
            $this->stories[] = json_decode(file_get_contents($file), true);
        }
    }

    private function calculateStats() {
        $totalChapters = 0;
        $totalWords = 0;
        $maxChapters = 0;
        $storyWithMostChapters = null;
        $lastUpdate = null;
        $mostRecentStory = null;
        $longestChapter = [
            'words' => 0,
            'story' => null,
            'chapter' => null
        ];

        foreach ($this->stories as $story) {
            // Compter les chapitres
            $chapterCount = count($story['chapters'] ?? []);
            $totalChapters += $chapterCount;

            // Trouver le roman avec le plus de chapitres
            if ($chapterCount > $maxChapters) {
                $maxChapters = $chapterCount;
                $storyWithMostChapters = $story;
            }

            // Trouver la dernière mise à jour
            $storyUpdate = strtotime($story['updated']);
            if (!$lastUpdate || $storyUpdate > $lastUpdate) {
                $lastUpdate = $storyUpdate;
                $mostRecentStory = $story;
            }

            // Compter les mots et trouver le plus long chapitre
            foreach ($story['chapters'] ?? [] as $chapter) {
                $content = $chapter['content'];
                
                // Si le contenu est au format JSON (Delta)
                if (is_string($content) && $this->isJson($content)) {
                    $content = json_decode($content, true);
                    $text = '';
                    if (isset($content['ops'])) {
                        foreach ($content['ops'] as $op) {
                            if (is_string($op['insert'])) {
                                $text .= $op['insert'];
                            }
                        }
                    }
                } else {
                    // Si le contenu est en HTML
                    $text = strip_tags($content);
                }

                $wordCount = str_word_count(strip_tags($text));
                $totalWords += $wordCount;

                if ($wordCount > $longestChapter['words']) {
                    $longestChapter = [
                        'words' => $wordCount,
                        'story' => $story,
                        'chapter' => $chapter
                    ];
                }
            }
        }

        $this->stats = [
            'total_stories' => count($this->stories),
            'total_chapters' => $totalChapters,
            'total_words' => $totalWords,
            'avg_chapters_per_story' => $this->stories ? round($totalChapters / count($this->stories), 1) : 0,
            'avg_words_per_chapter' => $totalChapters ? round($totalWords / $totalChapters) : 0,
            'most_chapters' => [
                'story' => $storyWithMostChapters,
                'count' => $maxChapters
            ],
            'longest_chapter' => $longestChapter,
            'latest_update' => [
                'story' => $mostRecentStory,
                'date' => $lastUpdate
            ]
        ];
    }

    public function getStats() {
        return $this->stats;
    }

    private function isJson($string) {
        json_decode($string);
        return json_last_error() === JSON_ERROR_NONE;
    }

    // Méthodes utilitaires pour le formatage
    public static function formatNumber($number) {
        return number_format($number, 0, ',', ' ');
    }

    public static function formatDate($timestamp) {
        if (!$timestamp) return 'Jamais';
        return date('d/m/Y', $timestamp);
    }
}