<?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\Services\AI;

use Illuminate\Support\Facades\Cache;
use Spatie\Activitylog\Models\Activity;

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

    /**
     * Analyze recent activity logs using AI.
     */
    public function analyzeRecentLogs(int $limit = 50): string
    {
        if (! get_setting('ai_enabled', false)) {
            return 'AI Service is currently disabled in system settings.';
        }

        $logs = Activity::with('causer')
            ->latest()
            ->take($limit)
            ->get()
            ->map(function ($log) {
                return [
                    'time' => $log->created_at->toDateTimeString(),
                    'user' => $log->causer ? $log->causer->name : 'System',
                    'action' => $log->description,
                    'subject' => $log->subject_type ? class_basename($log->subject_type) : 'N/A',
                ];
            })
            ->toArray();

        if (empty($logs)) {
            return 'No activity logs found to analyze.';
        }

        $prompt = 'As a Security and Operational Auditor, analyze the following system activity logs and provide:
        1. A brief summary of recent operations.
        2. Security insights (detect any suspicious patterns or potential privilege abuse).
        3. Operational health status.
        4. Recommendations (if any).

        FORMAT: Use Markdown with bold headers. Be concise and professional.
        
        LOGS DATA:
        '.json_encode($logs, JSON_PRETTY_PRINT);

        try {
            return Cache::remember('ai_log_analysis_result', 3600, function () use ($prompt) {
                $result = $this->aiService->provider()->generate($prompt);

                if (isset($result['success']) && $result['success']) {
                    return $result['response'] ?? 'AI failed to generate analysis.';
                }

                return 'AI Provider Error: '.($result['error'] ?? 'Unknown error');
            });
        } catch (\Exception $e) {
            return 'Error during AI analysis: '.$e->getMessage();
        }
    }
}
