<?php
namespace App\Services;

use App\Models\AiClassification;
use App\Models\AiKbDraft;
use App\Models\AiResponseTemplate;
use App\Models\KbArticle;
use App\Models\KbCategory;
use App\Models\Ticket;

class AiResponseService
{
    // ── FASE 3: Generar borrador de respuesta ─────────────────────────────────
    public function generateResponse(Ticket $ticket): ?array
    {
        $classification = $ticket->aiClassification;
        $template       = $this->findBestTemplate($ticket, $classification);

        if (!$template) return null;

        $body = $template->render($ticket, $classification);

        // Enriquecer con artículos KB relevantes
        $kbLinks = '';
        if ($classification && !empty($classification->kb_suggestions)) {
            $top = array_slice($classification->kb_suggestions, 0, 2);
            foreach ($top as $sug) {
                $kbLinks .= "\n- [{$sug['title']}]({$sug['url']})";
            }
        }
        if ($kbLinks) {
            $body .= "\n\n**Recursos que pueden ayudarte:**" . $kbLinks;
        }

        $template->increment('uses');

        return [
            'template_id'   => $template->id,
            'template_name' => $template->name,
            'body'          => $body,
            'confidence'    => $classification?->category_confidence ?? 50,
            'kb_links'      => $classification?->kb_suggestions ?? [],
        ];
    }

    // ── Encontrar la plantilla más adecuada ───────────────────────────────────
    private function findBestTemplate(Ticket $ticket, ?AiClassification $classification): ?AiResponseTemplate
    {
        $text = strtolower($ticket->title . ' ' . $ticket->description);

        $templates = AiResponseTemplate::active()
            ->when($ticket->category_id, fn($q) =>
                $q->where(fn($inner) =>
                    $inner->where('category_id', $ticket->category_id)->orWhereNull('category_id')
                )
            )
            ->get();

        $best      = null;
        $bestScore = 0;

        foreach ($templates as $template) {
            // Verificar confianza mínima
            $confidence = $classification?->category_confidence ?? 0;
            if ($confidence < $template->min_confidence && $template->min_confidence > 0) continue;

            $score = 0;
            foreach ($template->trigger_keywords as $kw) {
                if (str_contains($text, strtolower($kw))) {
                    $score += strlen($kw) > 6 ? 2 : 1; // Keywords largas valen más
                }
            }

            // Boost por categoría exacta
            if ($ticket->category_id && $template->category_id === $ticket->category_id) $score += 3;

            // Boost por tipo de ticket
            if ($ticket->type && $template->ticket_type && stripos($ticket->type->name, $template->ticket_type) !== false) $score += 2;

            // Boost por aceptación histórica
            $score += min(2, $template->accept_rate / 20);

            if ($score > $bestScore) {
                $bestScore = $score;
                $best      = $template;
            }
        }

        return $best;
    }

    // ── FASE 4: Generar borrador de artículo KB al cerrar ticket ─────────────
    public function generateKbDraft(Ticket $ticket): ?AiKbDraft
    {
        // Solo tickets con solución documentada (comentarios + categoría)
        if ($ticket->ai_kb_suggested) return null;
        if (!$ticket->category_id)    return null;

        $comments = $ticket->comments()
            ->where('is_internal', false)
            ->where('user_id', '!=', $ticket->requester_id)
            ->orderBy('created_at')
            ->get();

        if ($comments->isEmpty()) return null;

        // Construir contenido del artículo
        $title   = $this->generateTitle($ticket);
        $excerpt = $this->generateExcerpt($ticket);
        $content = $this->generateContent($ticket, $comments);
        $tags    = $this->extractTags($ticket);

        // Buscar categoría KB equivalente
        $kbCategory = $this->findKbCategory($ticket);

        $draft = AiKbDraft::create([
            'ticket_id'         => $ticket->id,
            'category_id'       => $kbCategory?->id,
            'suggested_title'   => $title,
            'suggested_excerpt' => $excerpt,
            'suggested_content' => $content,
            'suggested_tags'    => $tags,
            'status'            => 'pending',
        ]);

        $ticket->update(['ai_kb_suggested' => true]);

        return $draft;
    }

    // ── Publicar borrador como artículo KB ────────────────────────────────────
    public function publishDraft(AiKbDraft $draft, array $overrides = []): KbArticle
    {
        $article = KbArticle::create([
            'title'       => $overrides['title']   ?? $draft->suggested_title,
            'excerpt'     => $overrides['excerpt']  ?? $draft->suggested_excerpt,
            'content'     => $overrides['content']  ?? $draft->suggested_content,
            'category_id' => $overrides['category_id'] ?? $draft->category_id,
            'author_id'   => auth()->id(),
            'tags'        => implode(',', $draft->suggested_tags ?? []),
            'status'      => 'published',
            'published_at'=> now(),
        ]);

        $draft->update(['status' => 'published', 'published_article_id' => $article->id]);

        return $article;
    }

    // ── Helpers para generar contenido ───────────────────────────────────────
    private function generateTitle(Ticket $ticket): string
    {
        $title = $ticket->title;
        // Limpiar prefijos comunes de tickets
        $prefixes = ['Como', 'Error en', 'Problema con', 'No funciona', 'Falla en'];
        $title    = trim($title);
        // Convertir pregunta en guía
        if (str_ends_with($title, '?')) {
            return 'Cómo resolver: ' . rtrim($title, '?');
        }
        return 'Guía: ' . $title;
    }

    private function generateExcerpt(Ticket $ticket): string
    {
        $desc = strip_tags($ticket->description);
        $desc = preg_replace('/\s+/', ' ', trim($desc));
        return mb_strlen($desc) > 200 ? mb_substr($desc, 0, 197) . '...' : $desc;
    }

    private function generateContent(Ticket $ticket, $comments): string
    {
        $lines = [];
        $lines[] = "## Descripción del problema";
        $lines[] = "";
        $lines[] = trim(strip_tags($ticket->description));
        $lines[] = "";
        $lines[] = "## Solución";
        $lines[] = "";

        $solutionComments = $comments->filter(fn($c) =>
            mb_strlen($c->body) > 30 &&
            !str_contains(strtolower($c->body), 'gracias') &&
            !str_contains(strtolower($c->body), 'recibido')
        );

        foreach ($solutionComments as $comment) {
            $lines[] = trim(strip_tags($comment->body));
            $lines[] = "";
        }

        $lines[] = "## Información adicional";
        $lines[] = "";
        $lines[] = "- **Categoría:** " . ($ticket->category?->name ?? 'General');
        $lines[] = "- **Tipo:** " . ($ticket->type?->name ?? 'General');
        $lines[] = "- **Generado a partir del ticket:** " . $ticket->number;

        return implode("\n", $lines);
    }

    private function extractTags(Ticket $ticket): array
    {
        $tags = [];
        if ($ticket->category) $tags[] = strtolower($ticket->category->name);
        if ($ticket->type)     $tags[] = strtolower($ticket->type->name);

        $classification = $ticket->aiClassification;
        if ($classification && !empty($classification->keywords_detected)) {
            $keywords = array_filter($classification->keywords_detected, fn($k) => !str_contains($k, ' '));
            foreach (array_slice($keywords, 0, 3) as $kw) {
                $tags[] = $kw;
            }
        }
        return array_unique(array_slice($tags, 0, 6));
    }

    private function findKbCategory(Ticket $ticket): ?KbCategory
    {
        if (!$ticket->category) return null;
        $name = $ticket->category->name;
        return KbCategory::where('name', 'like', '%' . explode(' ', $name)[0] . '%')
            ->orWhere('name', $name)
            ->first();
    }
}
