<?php
namespace Database\Seeders;

use App\Models\AiKeywordRule;
use App\Models\TicketCategory;
use App\Models\TicketPriority;
use Illuminate\Database\Seeder;

class AiKeywordSeeder extends Seeder
{
    public function run(): void
    {
        $priorities = TicketPriority::all();
        $categories = TicketCategory::all();

        $findP = fn(string $hint) => $priorities->first(fn($p) => stripos($p->name, $hint) !== false);
        $findC = fn(array $hints) => $categories->first(fn($c) => collect($hints)->contains(fn($h) => stripos($c->name, $h) !== false));

        // Prioridades
        $pRules = [
            ['critica','caido','caída','no funciona','bloqueado','urgente','critico','fallo total','produccion','servidor caido','sistema caido'],
            ['alta','error','falla','no puedo','no tengo acceso','problema grave','afecta','importante','imposible trabajar','no abre'],
            ['media','lento','demora','intermitente','a veces','ocasional','tarda','lentitud','de vez en cuando'],
            ['baja','consulta','pregunta','informacion','como','quisiera','mejora','sugerencia','cuando pueda','seria bueno'],
        ];
        foreach ($pRules as $group) {
            $hint = array_shift($group);
            $p = $findP($hint);
            if (!$p) continue;
            foreach ($group as $kw) {
                AiKeywordRule::firstOrCreate(
                    ['keyword'=>$kw,'entity_type'=>'priority','entity_id'=>$p->id],
                    ['weight'=> str_word_count($kw)>1 ? 2.0 : 1.5, 'active'=>true]
                );
            }
        }

        // Categorías
        $cRules = [
            [['hardware','equipo','pc','computador'],   ['computador','pc','portatil','laptop','teclado','mouse','monitor','pantalla','impresora','disco duro','memoria','bateria','cable','equipo','maquina']],
            [['red','conectividad','internet','wifi'],   ['internet','red','wifi','conexion','vpn','router','switch','firewall','ethernet','dns','sin conexion','cable red']],
            [['software','aplicacion','programa'],       ['programa','aplicacion','app','software','instalar','actualizar','licencia','office','word','excel','error programa','no abre','windows']],
            [['correo','email','outlook'],               ['correo','email','gmail','outlook','no recibo','no envio','spam','bandeja','adjunto','calendario','exchange']],
            [['acceso','contrasena','password'],         ['contrasena','password','clave','acceso','usuario','login','sesion','bloqueo','no puedo entrar','resetear','cambiar clave','credenciales']],
            [['seguridad','virus'],                      ['virus','malware','ransomware','antivirus','phishing','estafa','correo sospechoso','robo','hacker','seguridad','backup','respaldo']],
        ];
        foreach ($cRules as [$hints, $keywords]) {
            $c = $findC($hints);
            if (!$c) continue;
            foreach ($keywords as $kw) {
                AiKeywordRule::firstOrCreate(
                    ['keyword'=>$kw,'entity_type'=>'category','entity_id'=>$c->id],
                    ['weight'=> str_word_count($kw)>1 ? 2.5 : 1.5, 'active'=>true]
                );
            }
        }

        echo '  AiKeywordSeeder: ' . AiKeywordRule::count() . " reglas creadas\n";
    }
}
