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(); } } }