<?php

namespace Drupal\api_monitor_ai\Controller;

use Drupal\ai_agents\PluginInterfaces\AiAgentInterface;
use Drupal\ai_agents\PluginManager\AiAgentManager;
use Drupal\ai_agents\Task\Task;
use Drupal\api_monitor_client\ApiSnifferService;
use Drupal\Core\Controller\ControllerBase;
use Drupal\api_monitor_ai\AiAssistantService;
use GuzzleHttp\Client;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Controller per l'Assistente AI.
 */
class AiAssistantController extends ControllerBase {

  /**
   * Costruttore AiAssistantController.
   */
  public function __construct(
    protected AiAssistantService $aiService,
    protected Client $httpClient,
    protected ApiSnifferService $apiRunner,
    protected AiAgentManager $agentsManager,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('api_monitor_ai.assistance_service'),
      $container->get('http_client'),
      $container->get('api_monitor_client.sniffer'),
      $container->get('plugin.manager.ai_agents')
    );
  }

  /**
   * Renderizza la pagina della chat.
   *
   * @param string|null $provider_id
   *   L'ID del provider opzionale.
   * @param string|null $api_id
   *   L'ID dell'API opzionale.
   */
  public function view($provider_id = NULL, $api_id = NULL) {
    return [
      '#theme' => 'api_monitor_ai_chat',
      '#provider_id' => $provider_id,
      '#api_id' => $api_id,
      '#attached' => [
        'library' => [
          'api_monitor_ai/chat_interface',
        ],
      ],
    ];
  }

  /**
   * Callback AJAX per processare la domanda.
   */
  public function ask(Request $request) {
    $question = $api_id = $provider_id = NULL;
    if ($content = $request->getContent()) {
      $data = json_decode($content, TRUE);
      if (!empty($data)) {
        $question = $data['question'] ?? NULL;
        $api_id = $data['api_id'] ?? NULL;
        $provider_id = $data['provider_id'] ?? NULL;
      }
    }

    if (empty($question)) {
      return new JsonResponse(['answer' => 'Per favore, scrivi una domanda.']);
    }

    // Se abbiamo un api_id, lo aggiungiamo al contesto della domanda per l'agente.
    if ($api_id && $api_id !== 'undefined' && $api_id !== 'null') {
      $question = "user_question: " . $question;
    }

    try {
      /** @var \Drupal\ai_agents\PluginInterfaces\AiAgentInterface $agent */
      $agent = $this->agentsManager->createInstance('api_monitor_agent');
      if ($api_id) {
        $agent->setData([
          'api_id' => $api_id,
          'provider_id' => $provider_id,
        ]);
      }
      $agent->setTask(new Task($question));

      // Determiniamo come l'agente deve rispondere.
      $can_solve = $agent->determineSolvability();

      if ($can_solve === AiAgentInterface::JOB_SOLVABLE) {
        $answer = $agent->solve();
      }
      elseif ($can_solve === AiAgentInterface::JOB_SHOULD_ANSWER_QUESTION) {
        $answer = $agent->answerQuestion();
      }
      else {
        // Fallback al servizio Groq se l'agente non è configurato per risolvere o rispondere.
        $aiResponse = $this->aiService->askAI($question, NULL, $api_id, $provider_id);
        $answer = $aiResponse['choices'][0]['message']['content'] ?? "Non sono riuscito a generare una risposta.";
      }

      return new JsonResponse([
        'answer' => $answer,
      ]);
    }
    catch (\Exception $e) {
      return new JsonResponse([
        'answer' => "Errore durante l'esecuzione dell'agente: " . $e->getMessage(),
      ], 500);
    }
  }

}
