<?php
/**
 * Shared helper for the "Explain this issue to me" feature.
 * Used by the customer and admin APIs. Calls the advanced model so the
 * end-user gets a thoughtful, non-jargon explanation.
 */

require_once(__DIR__ . '/litellm_client.php');

if (!function_exists('ai_monitor_explain_issue')) {

    function ai_monitor_explain_issue(array $issue): array {
        $title    = (string)($issue['title'] ?? '(untitled issue)');
        $severity = (string)($issue['severity'] ?? 'warning');
        $category = (string)($issue['category'] ?? '');
        $diag     = (string)($issue['diagnosis'] ?? '');
        $evidence = (string)($issue['evidence'] ?? '');
        $logExcerpt = (string)($issue['raw_log_excerpt'] ?? '');

        $prompt = <<<PROMPT
You are a friendly web-hosting support engineer explaining a detected issue
to a website owner who is NOT a system administrator. The user clicked
"Explain this to me" on the issue below.

Issue: {$title}
Severity: {$severity}
Category: {$category}

Technical diagnosis (from monitoring):
{$diag}

Evidence (verbatim log quote):
{$evidence}

Extra log context:
{$logExcerpt}

Please explain:
1. In plain language: what is happening on their site?
2. Why does it matter (or not matter) for visitors?
3. What should the site owner do next? Be concrete.
4. What we will do automatically, if anything.

Rules:
- Write for a non-technical reader. Avoid jargon. When you must use a
  technical term, define it in parentheses the first time.
- Stay grounded in the evidence and technical diagnosis above. Do not
  invent details. If something is unknown, say so.
- Keep it to roughly 150-250 words total.
- No code blocks, no JSON. Plain prose with short paragraphs.
PROMPT;

        $res = litellm_chat('advanced', [['role' => 'user', 'content' => $prompt]]);
        if (!$res['success']) {
            return ['success' => false, 'error' => $res['error']];
        }
        return [
            'success'     => true,
            'explanation' => $res['content'],
            'model'       => $res['model'],
        ];
    }
}
