<?php

namespace Database\Seeders;

use App\Models\HexlingBadge;
use App\Models\HexlingWord;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class HexlingWordSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        // Clear existing data
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        DB::table('hexling_badge_hexling_word')->truncate();
        HexlingBadge::truncate();
        HexlingWord::truncate();
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        // Seed Badges
        $badges = [
            [
                'badge_name' => 'Word Novice',
                'badge_description' => 'Complete your first word puzzle',
                'badge_image' => 'badge_novice.png',
                'badge_points' => 10,
                'badge_order' => 1,
            ],
            [
                'badge_name' => 'Word Explorer',
                'badge_description' => 'Solve 10 different word puzzles',
                'badge_image' => 'badge_explorer.png',
                'badge_points' => 25,
                'badge_order' => 2,
            ],
            [
                'badge_name' => 'Word Master',
                'badge_description' => 'Solve 50 word puzzles with perfect score',
                'badge_image' => 'badge_master.png',
                'badge_points' => 100,
                'badge_order' => 3,
            ],
            [
                'badge_name' => 'Hex Champion',
                'badge_description' => 'Complete all levels in a hex puzzle',
                'badge_image' => 'badge_champion.png',
                'badge_points' => 50,
                'badge_order' => 4,
            ],
            [
                'badge_name' => 'Speed Solver',
                'badge_description' => 'Solve a puzzle in under 2 minutes',
                'badge_image' => 'badge_speed.png',
                'badge_points' => 30,
                'badge_order' => 5,
            ],
            [
                'badge_name' => 'Vocabulary King',
                'badge_description' => 'Find all possible words in a puzzle',
                'badge_image' => 'badge_vocab_king.png',
                'badge_points' => 75,
                'badge_order' => 6,
            ],
            [
                'badge_name' => 'Streak Builder',
                'badge_description' => 'Solve puzzles for 7 consecutive days',
                'badge_image' => 'badge_streak.png',
                'badge_points' => 40,
                'badge_order' => 7,
            ],
            [
                'badge_name' => 'Puzzle Collector',
                'badge_description' => 'Play 100 different puzzles',
                'badge_image' => 'badge_collector.png',
                'badge_points' => 150,
                'badge_order' => 8,
            ],
        ];

        foreach ($badges as $badge) {
            HexlingBadge::create($badge);
        }

        $this->command->info('Hexling badges seeded successfully!');

        $commonRootWords = [
            'basket', 'garden', 'market', 'puzzle', 'rocket', 'summer', 'winter', 'spring',
            'autumn', 'circle', 'square', 'master', 'planet', 'forest', 'castle', 'button',
            'camera', 'dollar', 'energy', 'flower', 'guitar', 'hammer', 'island', 'jacket',
            'kettle', 'laptop', 'mirror', 'needle', 'orange', 'pencil', 'quilt', 'rabbit',
            'silver', 'ticket', 'umbrella', 'violin', 'window', 'yellow', 'anchor', 'bottle',
            'candle', 'dragon', 'finger', 'goblin', 'hunter', 'insect', 'jigsaw', 'knight',
            'lemon', 'monkey', 'napkin', 'octopus', 'penguin', 'quilt', 'ruler', 'spider',
            'turtle', 'violet', 'whistle', 'xylophone', 'yogurt', 'zipper', 'bracket', 'circus',
            'dynamo', 'echoes', 'falcon', 'goblet', 'hijack', 'jockey', 'kelvin', 'locket',
            'magnet', 'nymphs', 'oxygen', 'phoenix', 'quicks', 'rocket', 'sphinx', 'trophy',
            'unique', 'vortex', 'wizard', 'yachts', 'zephyr', 'ambush', 'beyond', 'cipher',
            'desert', 'exotic', 'frozen', 'glitch', 'honest', 'impact', 'jungle', 'kernel',
            'luxury', 'mythic', 'nectar', 'oracle', 'phantom', 'quartz', 'rhythm', 'sacred',
            'temple', 'utopia', 'voyage', 'wrest', 'xenon', 'yields', 'zenith',
        ];

        // Filter to ensure no duplicate letters
        $filteredRootWords = array_filter($commonRootWords, function ($word) {
            return count(array_unique(str_split($word))) === strlen($word);
        });

        $centerLetters = ['a', 'e', 'i', 'o', 'u', 'r', 't', 'n', 's', 'l', 'c', 'p', 'm', 'd', 'g', 'b'];

       $wordCombinations = [
            'basket' => [
                'r' => ['baker', 'bakes', 'barke', 'basks', 'beast', 'beats', 'beret', 'beset', 'betas', 'brake', 'brats', 'break', 'stake', 'stare', 'steak', 'strake', 'streak', 'taber', 'taker', 'takes', 'taser', 'teaks', 'trades'],
                'l' => ['bakes', 'bales', 'balsa', 'bases', 'basil', 'basin', 'basks', 'beaks', 'beals', 'bells', 'belts', 'blase', 'blasts', 'bleak', 'bleats', 'bless', 'blest', 'blots', 'bolts', 'stale', 'stall', 'steal', 'stela', 'tables', 'tales', 'talks', 'talls', 'teals'],
            ],
            'garden' => [
                'e' => ['anger', 'angel', 'angle', 'dange', 'gader', 'gared', 'grade', 'raged', 'range', 'redan', 'regna', 'derng', 'garde', 'genar', 'geran', 'nadge', 'raged'],
                'i' => ['aging', 'aider', 'aired', 'anger', 'aring', 'daing', 'daring', 'dinar', 'dinge', 'drain', 'garni', 'grade', 'grained', 'grand', 'grind', 'raing', 'range', 'ringed'],
            ],
            'market' => [
                'e' => ['maker', 'taker', 'rate', 'mate', 'team', 'meat', 'tame', 'mare', 'ream', 'armet', 'merkat', 'ramet', 'tamer'],
                'i' => ['maker', 'taker', 'rate', 'mate', 'team', 'meat', 'tame', 'mare', 'ream', 'armet', 'merkat', 'ramet', 'tamer'],
            ],
            'puzzle' => [
                'r' => ['peruz', 'puler', 'pure', 'rule', 'lure', 'rep', 'zel', 'pez'],
                'e' => ['peel', 'pule', 'zele', 'luz', 'pez', 'zee', 'leu', 'ule', 'pel', 'zep'],
            ],
            'rocket' => [
                'e' => ['ocker', 'core', 'cork', 'cote', 'reck', 'rock', 'rote', 'tock', 'toke', 'tore', 'coker', 'recto', 'toker'],
                'i' => ['citer', 'coke', 'cote', 'cork', 'reck', 'rock', 'rote', 'tock', 'toke', 'tore', 'coker', 'recto', 'toker'],
            ],
            'summer' => [
                'e' => ['emmer', 'meres', 'merse', 'mesem', 'muser', 'resue', 'reuse', 'rumes', 'serum', 'suer', 'sumer', 'urems', 'users'],
                'a' => ['amuse', 'mares', 'marse', 'maser', 'mures', 'muser', 'ramus', 'reams', 'rumes', 'serum', 'suer', 'sumer', 'urems', 'users'],
            ],
            'winter' => [
                'e' => ['inert', 'inter', 'niter', 'nitre', 'trine', 'twier', 'twine', 'winer', 'witen', 'wrier', 'write', 'writ', 'twin', 'tine', 'rine', 'wite'],
                'a' => ['antre', 'inert', 'inter', 'niter', 'nitre', 'trine', 'twier', 'twine', 'winer', 'witen', 'wrier', 'write', 'writ', 'twin', 'tine', 'rine', 'wite'],
            ],
            'spring' => [
                'e' => ['ering', 'girns', 'grins', 'prigs', 'rings', 'sering'],
                'a' => ['aping', 'girns', 'grins', 'prigs', 'rings', 'sering'],
            ],
            'circle' => [
                'e' => ['ceric', 'cicer', 'circe', 'creel'],
                'a' => ['acier', 'areic', 'ceria', 'craie', 'creel'],
            ],
            'master' => [
                'e' => ['amster', 'armets', 'master', 'maters', 'ramets', 'stream', 'tamers', 'armet', 'mares', 'marse', 'maser', 'mater', 'mates', 'meats', 'ramet', 'rates', 'reams', 'resat', 'satem', 'stare', 'steam', 'tamer', 'tames', 'teams', 'teras', 'tram', 'tres'],
                'i' => ['aimers', 'amires', 'armies', 'maries', 'marses', 'masers', 'misers', 'ramies', 'remiss', 'samier', 'seimas', 'simars', 'smears', 'aimer', 'amies', 'amiss', 'arise', 'arses', 'emirs', 'iraes', 'mares', 'marse', 'maser', 'mises', 'raies', 'ramie', 'rases', 'reams', 'rises', 'saris', 'seams', 'sears', 'seism', 'semis', 'serai', 'sires', 'smear', 'stair', 'stare', 'steam', 'stime', 'tamer', 'tames', 'teams', 'teras', 'times', 'tram', 'tres'],
            ],
        ];

        // Generate games
        $startDate = Carbon::now()->subDays(30);
        $endDate = Carbon::now();
        $games = [];
        $gameIdCounter = 1000;

        for ($date = $startDate->copy(); $date->lte($endDate); $date->addDay()) {
            $rootWord = $filteredRootWords[array_rand($filteredRootWords)];

            $availableCenters = isset($wordCombinations[$rootWord]) ?
                array_keys($wordCombinations[$rootWord]) : $centerLetters;

            $centerLetter = $availableCenters[array_rand($availableCenters)];

            while (strpos($rootWord, $centerLetter) !== false) {
                $centerLetter = $centerLetters[array_rand($centerLetters)];
            }

            if (isset($wordCombinations[$rootWord][$centerLetter])) {
                $secretWords = $wordCombinations[$rootWord][$centerLetter];
            } else {
                $secretWords = $this->generateSecretWords($rootWord, $centerLetter);
            }

            $secretWords = array_filter($secretWords, function ($word) {
                return strlen($word) >= 4;
            });

            if (count($secretWords) < 8) {
                $additionalWords = $this->generateSecretWords($rootWord, $centerLetter);
                $secretWords = array_merge($secretWords, $additionalWords);
                $secretWords = array_unique($secretWords);
                $secretWords = array_filter($secretWords, function ($word) {
                    return strlen($word) >= 4;
                });
            }

            $secretWords = array_slice($secretWords, 0, rand(8, 12));

            $gameId = $gameIdCounter++;

            $games[] = [
                'game_id' => $gameId,
                'root_word' => $rootWord,
                'center_letter' => $centerLetter,
                'secret_words' => json_encode($secretWords),
                'total_levels' => 0, // Initialize as 0, will be updated after badge attachment
                'total_points' => 0, // Initialize as 0, will be updated after badge attachment
                'game_date' => $date->toDateString(),
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        // Insert all games first
        HexlingWord::insert($games);

        // Attach badges to words and calculate total levels & points
        $this->attachBadgesToWords();
    }

     private function generateSecretWords(string $rootWord, string $centerLetter): array
    {
        // Common English words that can be formed
        $commonEnglishWords = [
            'able', 'about', 'above', 'actor', 'acute', 'admit', 'adopt', 'adult', 'after', 'again',
            'agent', 'agree', 'ahead', 'alarm', 'album', 'alert', 'alien', 'align', 'alive', 'allow',
            'alone', 'along', 'alter', 'angel', 'anger', 'angle', 'angry', 'apart', 'apple', 'apply',
            'area', 'arena', 'argue', 'arise', 'array', 'aside', 'asset', 'audio', 'audit', 'avoid',
            'award', 'aware', 'badly', 'baker', 'bases', 'basic', 'beach', 'began', 'being', 'below',
            'bench', 'billy', 'birth', 'black', 'blame', 'blind', 'block', 'blood', 'board', 'boost',
            'booth', 'bound', 'brain', 'brand', 'brave', 'bread', 'break', 'breed', 'brief', 'bring',
            'broad', 'broke', 'brown', 'build', 'built', 'buyer', 'cable', 'calif', 'carry', 'catch',
            'cause', 'chain', 'chair', 'chaos', 'charm', 'chart', 'chase', 'cheap', 'check', 'chest',
            'chief', 'child', 'china', 'chose', 'civil', 'claim', 'class', 'clean', 'clear', 'click',
            'clock', 'close', 'cloud', 'coach', 'coast', 'could', 'count', 'court', 'cover', 'craft',
            'crash', 'crazy', 'cream', 'crime', 'cross', 'crowd', 'crown', 'crude', 'curve', 'cycle',
            'daily', 'dance', 'dated', 'dealt', 'death', 'debts', 'debug', 'debut', 'delay', 'depth',
            'doing', 'doubt', 'dozen', 'draft', 'drama', 'drank', 'drawn', 'dream', 'dress', 'drill',
            'drink', 'drive', 'drove', 'dying', 'eager', 'early', 'earth', 'eight', 'elite', 'empty',
            'enemy', 'enjoy', 'enter', 'entry', 'equal', 'error', 'event', 'every', 'exact', 'exist',
            'extra', 'faith', 'false', 'fault', 'fiber', 'field', 'fifth', 'fifty', 'fight', 'final',
            'first', 'fixed', 'flash', 'fleet', 'floor', 'fluid', 'focus', 'force', 'forth', 'forty',
            'forum', 'found', 'frame', 'frank', 'fraud', 'fresh', 'front', 'fruit', 'fully', 'funny',
            'giant', 'given', 'glass', 'globe', 'going', 'grace', 'grade', 'grand', 'grant', 'grass',
            'grave', 'great', 'green', 'gross', 'group', 'grown', 'guard', 'guess', 'guest', 'guide',
            'happy', 'harry', 'heart', 'heavy', 'hello', 'henry', 'horse', 'hotel', 'house', 'human',
            'ideal', 'image', 'imply', 'index', 'inner', 'input', 'issue', 'japan', 'jimmy', 'joint',
            'jones', 'judge', 'known', 'label', 'large', 'laser', 'later', 'laugh', 'layer', 'learn',
            'lease', 'least', 'leave', 'legal', 'lemon', 'level', 'lewis', 'light', 'limit', 'links',
            'lives', 'local', 'logic', 'loose', 'lower', 'lucky', 'lunch', 'lying', 'magic', 'major',
            'maker', 'march', 'maria', 'match', 'maybe', 'mayor', 'meant', 'media', 'metal', 'might',
            'minor', 'minus', 'mixed', 'model', 'money', 'month', 'moral', 'motor', 'mount', 'mouse',
            'mouth', 'moved', 'movie', 'music', 'needs', 'never', 'newly', 'night', 'noise', 'north',
            'noted', 'novel', 'nurse', 'occur', 'ocean', 'offer', 'often', 'order', 'other', 'ought',
            'outer', 'owner', 'paint', 'panel', 'paper', 'party', 'peace', 'penny', 'peter', 'phase',
            'phone', 'photo', 'piano', 'piece', 'pilot', 'pitch', 'place', 'plain', 'plane', 'plant',
            'plate', 'point', 'pound', 'power', 'press', 'price', 'pride', 'prime', 'print', 'prior',
            'prize', 'proof', 'proud', 'prove', 'queen', 'quick', 'quiet', 'quite', 'radio', 'raise',
            'range', 'rapid', 'ratio', 'reach', 'ready', 'realm', 'refer', 'relax', 'repay', 'reply',
            'right', 'rival', 'river', 'robin', 'rocky', 'roger', 'roman', 'rough', 'round', 'route',
            'royal', 'rural', 'scale', 'scene', 'scope', 'score', 'screw', 'sense', 'serve', 'seven',
            'shall', 'shape', 'share', 'sharp', 'sheet', 'shelf', 'shell', 'shift', 'shine', 'shirt',
            'shock', 'shoot', 'short', 'shown', 'sight', 'silver', 'similar', 'simple', 'since', 'sixth',
            'sixty', 'sized', 'skill', 'slash', 'sleep', 'slide', 'small', 'smart', 'smile', 'smith',
            'smoke', 'solid', 'solve', 'sorry', 'sound', 'south', 'space', 'spare', 'speak', 'speed',
            'spend', 'spent', 'split', 'spoke', 'sport', 'staff', 'stage', 'stake', 'stand', 'start',
            'state', 'steam', 'steel', 'steep', 'steer', 'stick', 'still', 'stock', 'stone', 'stood',
            'store', 'storm', 'story', 'strip', 'stuck', 'study', 'stuff', 'style', 'sugar', 'suite',
            'sunny', 'super', 'surge', 'sweet', 'swift', 'swing', 'sword', 'table', 'taken', 'taste',
            'taxes', 'teach', 'teeth', 'tempo', 'texas', 'thank', 'theft', 'their', 'theme', 'there',
            'these', 'thick', 'thing', 'think', 'third', 'those', 'three', 'threw', 'throw', 'thumb',
            'tight', 'timer', 'title', 'today', 'topic', 'total', 'touch', 'tough', 'tower', 'track',
            'trade', 'train', 'trash', 'treat', 'trend', 'trial', 'tribe', 'trick', 'tried', 'tries',
            'truck', 'truly', 'trust', 'truth', 'twice', 'twist', 'tyler', 'uncle', 'under', 'undue',
            'union', 'unity', 'until', 'upper', 'upset', 'urban', 'usage', 'usual', 'valid', 'value',
            'video', 'virus', 'visit', 'vital', 'vocal', 'voice', 'wagon', 'waste', 'watch', 'water',
            'wheel', 'where', 'which', 'while', 'white', 'whole', 'whose', 'woman', 'women', 'world',
            'worry', 'worse', 'worst', 'worth', 'would', 'wound', 'write', 'wrong', 'wrote', 'yield',
            'young', 'youth',
        ];

        // Filter words that contain the center letter and are 4+ letters
        $filteredWords = array_filter($commonEnglishWords, function ($word) use ($centerLetter) {
            return strlen($word) >= 4 && strpos($word, $centerLetter) !== false;
        });

        return array_slice($filteredWords, 0, rand(8, 15));
    }

    private function attachBadgesToWords()
    {
        $badges = HexlingBadge::all();
        $words = HexlingWord::all();

        foreach ($words as $word) {
            $randomBadges = $badges->random(rand(1, 3));

            $totalBadgePoints = 0;
            $attachedBadges = [];
            $badgeCount = 0;

            foreach ($randomBadges as $badge) {
                DB::table('hexling_badge_hexling_word')->insert([
                    'hexling_words_id' => $word->id,
                    'hexling_badges_id' => $badge->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                $totalBadgePoints += $badge->badge_points;
                $attachedBadges[] = $badge->badge_name;
                $badgeCount++;
            }

            // UPDATE: Total levels = number of badges attached to this word
            $totalLevels = $badgeCount;

            // Update the word with total badge points and total levels
            $word->update([
                'total_points' => $totalBadgePoints,
                'total_levels' => $totalLevels // NEW: Set total levels = badge count
            ]);
        }
    }
}
