<?php

namespace App\Controllers;

use App\Core\Controller;

class AIController extends Controller {
    
    public function chat() {
        header('Content-Type: application/json');
        
        $input = json_decode(file_get_contents('php://input'), true);
        $userMessage = $input['message'] ?? '';

        if (empty($userMessage)) {
            echo json_encode(['error' => 'Message is empty']);
            return;
        }

        require_once __DIR__ . '/../../ai/LocalAIApi.php';

        $systemPrompt = "You are a helpful assistant for " . get_setting('site_name', 'ApkNusa') . ", an APK downloader and tech blog site. Provide concise and accurate information about Android apps, games, and technology. Be youthful and professional.";

        $resp = \LocalAIApi::createResponse([
            'input' => [
                ['role' => 'system', 'content' => $systemPrompt],
                ['role' => 'user', 'content' => $userMessage],
            ],
        ]);

        if (!empty($resp['success'])) {
            $text = \LocalAIApi::extractText($resp);
            echo json_encode(['reply' => $text]);
        } else {
            echo json_encode(['error' => 'AI Assistant is currently unavailable.']);
        }
    }
}
