<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$auth = hw_auth_user();
if (!$auth) hw_json(['message' => 'Authentication required'], 401);

$input = hw_input_json();
$message = trim((string)($input['message'] ?? ''));
$action = $input['action'] ?? 'chat';

if ($message === '') hw_json(['message' => 'Message is required'], 422);

$cfg = hw_config();
$ai = $cfg['ai'] ?? [];
$apiKey = $ai['api_key'] ?: getenv('OPENAI_API_KEY');
if (!$apiKey) hw_json(['message' => 'AI provider not configured. Set OPENAI_API_KEY or api.ai.api_key in config.'], 500);

// Basic moderation: block simple substrings
$blocklist = $ai['moderation_blocklist'] ?? [];
foreach ($blocklist as $b) {
    if (stripos($message, $b) !== false) {
        hw_json(['message' => 'Content not allowed'], 403);
    }
}

// Simple per-user rate limiting using temp files (MVP)
$userId = (int)($auth['sub'] ?? 0);
$limit = (int)($ai['rate_limit_per_hour'] ?? 100);
$rateFile = sys_get_temp_dir() . "/hw_ai_rate_{$userId}.json";
$window = 3600; // 1 hour
$now = time();
$counts = ['timestamps' => []];
if (file_exists($rateFile)) {
    $raw = @file_get_contents($rateFile);
    $counts = json_decode($raw ?: '[]', true) ?: ['timestamps' => []];
    $counts['timestamps'] = array_filter($counts['timestamps'], fn($t) => ($now - (int)$t) < $window);
}
if (count($counts['timestamps']) >= $limit) {
    hw_json(['message' => 'Rate limit exceeded'], 429);
}
$counts['timestamps'][] = $now;
@file_put_contents($rateFile, json_encode($counts));

// Build provider request (OpenAI Chat Completions)
$model = $ai['model'] ?? 'gpt-3.5-turbo';
$system = "You are an assistant for A Taste of Africa Marketplace. Be concise and helpful.";

// Summarize action support
if (($input['action'] ?? '') === 'summarize') {
    $system = "You are a summarizer. Condense user intake into a short clinical summary (2-3 sentences). Keep PHI out of public text unless explicitly authorized.";
    $message = "Please summarize the following intake for a care provider:\n\n" . $message;
}

$payload = [
    'model' => $model,
    'messages' => [
        ['role' => 'system', 'content' => $system],
        ['role' => 'user', 'content' => $message],
    ],
    'max_tokens' => 512,
    'temperature' => 0.6,
];

$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$res = curl_exec($ch);
$err = curl_error($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($res === false || $code >= 400) {
    hw_json(['message' => 'AI provider error', 'error' => $err ?: $res], 502);
}

$json = json_decode($res ?: '{}', true) ?: [];
$text = '';
if (!empty($json['choices'][0]['message']['content'])) {
    $text = (string)$json['choices'][0]['message']['content'];
}

hw_json(['message' => $text]);
