<?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.
 */

if (!function_exists('ai_monitor_explain_issue')) {

    function ai_monitor_explain_issue(array $issue): array {
        $configFile = '/etc/whp/ai-monitor.conf';
        if (!file_exists($configFile)) {
            return ['success' => false, 'error' => 'AI monitor not configured on this server.'];
        }
        $config = parse_ini_file($configFile, true);
        $ai = $config['ai'] ?? [];
        $baseUrl    = rtrim($ai['base_url'] ?? '', '/');
        $apiKeyFile = $ai['api_key_file'] ?? '';
        $model      = $ai['advanced_model'] ?? ($ai['basic_model'] ?? '');
        if (!$baseUrl || !$apiKeyFile || !$model || !file_exists($apiKeyFile)) {
            return ['success' => false, 'error' => 'AI monitor credentials are incomplete.'];
        }
        $apiKey = trim(file_get_contents($apiKeyFile));
        if ($apiKey === '') {
            return ['success' => false, 'error' => 'AI API key missing.'];
        }

        $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;

        $payload = json_encode([
            'model'       => $model,
            'messages'    => [['role' => 'user', 'content' => $prompt]],
        ]);

        $ch = curl_init($baseUrl . '/chat/completions');
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $payload,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 60,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $apiKey,
            ],
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err      = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            error_log('ai_monitor_explain_issue: curl error: ' . $err);
            return ['success' => false, 'error' => 'Could not reach the AI service.'];
        }
        if ($httpCode !== 200) {
            error_log('ai_monitor_explain_issue: HTTP ' . $httpCode . ': ' . substr((string)$response, 0, 300));
            return ['success' => false, 'error' => 'AI service returned HTTP ' . $httpCode . '.'];
        }
        $data = json_decode($response, true);
        $content = $data['choices'][0]['message']['content'] ?? '';
        if ($content === '') {
            return ['success' => false, 'error' => 'AI service returned an empty response.'];
        }
        return [
            'success'     => true,
            'explanation' => trim($content),
            'model'       => $data['model'] ?? $model,
        ];
    }
}
