<?php

/**
 * ============================================================
 *
 * @project   biiproject
 *
 * @author    Andika Debi Putra
 *
 * @email     andikadebiputra@gmail.com
 *
 * @website   https://biiproject.com
 *
 * @copyright Copyright (c) 2026 Andika Debi Putra
 * @license   Proprietary - All Rights Reserved
 *
 * @version   1.0.0
 *
 * @created   2026-05-01
 * ============================================================
 */

namespace App\Listeners;

use App\Models\User;
use App\Notifications\SystemManagementNotification;
use App\Services\AI\AiService;
use Illuminate\Log\Events\MessageLogged;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class AnalyzeSystemError
{
    public function __construct(
        protected AiService $aiService
    ) {}

    /**
     * Handle the event.
     */
    public function handle(MessageLogged $event): void
    {
        // Only analyze errors/critical/alert/emergency
        if (! in_array($event->level, ['error', 'critical', 'alert', 'emergency'])) {
            return;
        }

        // Avoid infinite loops if AI service itself fails
        if (str_contains($event->message, 'AI Analysis')) {
            return;
        }

        if (! get_setting('ai_healing_enabled', false)) {
            return;
        }

        // Limit analysis to once per 5 minutes for the same error message to save tokens
        $cacheKey = 'ai_error_analysis_'.md5($event->message);
        if (Cache::has($cacheKey)) {
            return;
        }

        try {
            $prompt = "As a Senior DevOps Engineer, analyze this Laravel system error and provide a concise 'Root Cause' and 'Suggested Fix'.
            ERROR: [{$event->level}] {$event->message}
            CONTEXT: ".json_encode($event->context);

            $result = $this->aiService->provider()->generate($prompt);

            if (isset($result['success']) && $result['success']) {
                $analysis = $result['response'];

                // Cache it
                Cache::put($cacheKey, $analysis, 300);

                // Log the AI insight (quietly)
                Log::channel('single')->info('AI Analysis for Error: '.$analysis);

                $admins = User::role(['Developer', 'Administrator'])->get();
                foreach ($admins as $admin) {
                    $admin->notify(new SystemManagementNotification(
                        "AI Diagnostic: {$event->level} Detected",
                        $analysis,
                        'error',
                        'Developer'
                    ));
                }
            }
        } catch (\Exception $e) {
            // Silently fail to avoid loops
        }
    }
}
