<?php
namespace App\Http\Controllers;

use App\Models\AiClassification;
use App\Models\Ticket;
use App\Services\AiClassifierService;
use Illuminate\Http\Request;

class AiController extends Controller
{
    public function __construct(private AiClassifierService $ai) {}

    // GET /ai/suggest?text=... — sugerencias KB para texto libre (AJAX en ticket create)
    public function suggest(Request $request)
    {
        $request->validate(['text' => 'required|string|min:5']);
        $suggestions = $this->ai->suggestKbForText($request->text, 5);
        return response()->json(['success' => true, 'data' => $suggestions]);
    }

    // POST /ai/classify/{ticket} — clasificar ticket (llamado internamente)
    public function classify(Ticket $ticket)
    {
        abort_unless(auth()->user()->hasAnyRole(['agente','jefe_soporte','admin','superadmin']), 403);
        $classification = $this->ai->classify($ticket);
        $classification->load(['suggestedCategory','suggestedPriority']);

        return response()->json([
            'success' => true,
            'data'    => [
                'category' => $classification->suggestedCategory
                    ? ['id' => $classification->suggested_category_id, 'name' => $classification->suggestedCategory->name, 'confidence' => $classification->category_confidence]
                    : null,
                'priority' => $classification->suggestedPriority
                    ? ['id' => $classification->suggested_priority_id, 'name' => $classification->suggestedPriority->name, 'confidence' => $classification->priority_confidence]
                    : null,
                'kb_suggestions'  => $classification->kb_suggestions ?? [],
                'keywords'        => $classification->keywords_detected ?? [],
                'is_confident'    => $classification->is_confident,
            ],
        ]);
    }

    // POST /ai/feedback/{classification} — aceptar o rechazar sugerencia
    public function feedback(Request $request, AiClassification $classification)
    {
        abort_unless(auth()->user()->hasAnyRole(['agente','jefe_soporte','admin','superadmin']), 403);
        $data = $request->validate([
            'action'              => 'required|in:accept,reject',
            'correct_category_id' => 'nullable|exists:ticket_categories,id',
            'correct_priority_id' => 'nullable|exists:ticket_priorities,id',
        ]);

        if ($data['action'] === 'accept') {
            $this->ai->applySuggestion($classification);
            $msg = 'Sugerencia aceptada. El modelo ha sido reforzado.';
        } else {
            $this->ai->rejectSuggestion($classification, $data['correct_category_id'] ?? null, $data['correct_priority_id'] ?? null);
            $msg = 'Sugerencia rechazada. El modelo ha aprendido la corrección.';
        }

        return response()->json(['success' => true, 'message' => $msg]);
    }

    // GET /ai/admin — panel de administración de IA
    public function admin()
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);

        $totalClassifications = AiClassification::count();
        $accepted             = AiClassification::where('applied', true)->count();
        $accuracy             = $totalClassifications > 0 ? round(($accepted / $totalClassifications) * 100) : 0;
        $avgCatConfidence     = round(AiClassification::avg('category_confidence') ?? 0);
        $avgPriConfidence     = round(AiClassification::avg('priority_confidence') ?? 0);
        $recentClassifications= AiClassification::with(['ticket','suggestedCategory','suggestedPriority'])->latest()->limit(10)->get();

        return view('ai.admin', compact(
            'totalClassifications','accepted','accuracy',
            'avgCatConfidence','avgPriConfidence','recentClassifications'
        ));
    }

    // POST /ai/retrain
    public function retrain()
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);

        $tickets = \App\Models\Ticket::with(['category','priority'])
            ->whereNotNull('category_id')
            ->limit(200)->get();

        $learned = 0;
        foreach ($tickets as $ticket) {
            try {
                $cl = $this->ai->classify($ticket);
                if ($cl->suggested_category_id !== $ticket->category_id) {
                    $this->ai->rejectSuggestion($cl, $ticket->category_id, $ticket->priority_id);
                } else {
                    $this->ai->applySuggestion($cl);
                }
                $learned++;
            } catch (\Throwable $e) {}
        }

        return response()->json(['success' => true, 'message' => "Entrenamiento completado con {$learned} tickets."]);
    }

}