<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\Auth;
use App\Core\Controller;
use App\Core\Permission;
use App\Services\AiSecurityAssistantService;
final class AiSecurityAssistantController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('soc.ai.view');
        $service=new AiSecurityAssistantService();
        $this->view('security/ai_security_assistant',[
            'pageTitle'=>'AI Security Assistant',
            'dashboard'=>$service->dashboard(),
            'answer'=>null,
            'question'=>'',
        ]);
    }
    public function ask(): void
    {
        Auth::requireLogin();
        Permission::require('soc.ai.use');
        $question=trim((string)($_POST['question']??''));
        if($question===''){http_response_code(422);$answer=['status'=>'error','text'=>'La question est obligatoire.'];}
        elseif(mb_strlen($question)>2000){http_response_code(422);$answer=['status'=>'error','text'=>'La question dépasse 2 000 caractères.'];}
        else{$answer=(new AiSecurityAssistantService())->ask($question,Auth::id());}
        $service=new AiSecurityAssistantService();
        $this->view('security/ai_security_assistant',[
            'pageTitle'=>'AI Security Assistant','dashboard'=>$service->dashboard(),'answer'=>$answer,'question'=>$question,
        ]);
    }
    public function saveSettings(): void
    {
        Auth::requireLogin();
        Permission::require('soc.ai.manage');
        (new AiSecurityAssistantService())->saveSettings([
            'enabled'=>(int)($_POST['enabled']??0),
            'provider'=>(string)($_POST['provider']??'local'),
            'model'=>(string)($_POST['model']??'axiom-security-local'),
            'endpoint'=>(string)($_POST['endpoint']??''),
            'allow_external'=>(int)($_POST['allow_external']??0),
            'anonymize'=>(int)($_POST['anonymize']??1),
        ],Auth::id());
        header('Location: /public/administration/securite/assistant-ia?saved=1');exit;
    }
    public function clearHistory(): void
    {
        Auth::requireLogin();
        Permission::require('soc.ai.manage');
        (new AiSecurityAssistantService())->clearHistory();
        header('Location: /public/administration/securite/assistant-ia?cleared=1');exit;
    }
}
