<?php

declare(strict_types=1);

namespace App\Controller;

use ApiPlatform\Validator\ValidatorInterface;
use App\Dto\Input\DeployImageInput;
use App\Dto\Output\ClientOutput;
use App\Entity\Trace;
use App\Model\ImageStatus;  
use App\Entity\ImageImageRepository;
use App\Model\CommandTypes;
use App\Model\DeployMethodTypes;
use App\Model\TraceStatus;
use App\Service\Trace\CreateService;
use App\Repository\ClientRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class DeployImageAction extends AbstractController
{
    public function __construct(
        protected readonly EntityManagerInterface $entityManager,
        protected readonly HttpClientInterface    $httpClient,
        protected readonly CreateService          $createService,
        protected readonly ValidatorInterface     $validator,
        protected readonly ClientRepository       $clientRepository,
        protected readonly LoggerInterface        $logger,
        public readonly \App\Controller\OgAgent\DeployImageAction $deployImageOgAgentAction,
        public readonly \App\Controller\OgRepository\Image\DeployImageAction $deployImageOgRepositoryAction,
    ) {
    }

    /**
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     * @throws ServerExceptionInterface
     */
    public function __invoke(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): JsonResponse
    {
        if ($image->getStatus() !== ImageStatus::SUCCESS) {
            throw new BadRequestHttpException('Image is not ready to be deployed');
        }
        
        $this->validator->validate($input);
        $clientJobs = [];

        if ($input->type === 'monolithic') {
            $clientJobs = $this->handleMonolithicDeployment($input, $image, $trace);
        }

        return new JsonResponse(data: $clientJobs, status: Response::HTTP_OK);
    }


    private function handleMonolithicDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
    {
        $clientJobs = [];

        switch ($input->method) {
            case DeployMethodTypes::UNICAST:
            case DeployMethodTypes::UNICAST_DIRECT:
                $clientJobs = $this->handleUnicastDeployment($input, $image, $trace);
                break;
            case DeployMethodTypes::MULTICAST_UFTP:
            case DeployMethodTypes::MULTICAST_UFTP_DIRECT:
            case DeployMethodTypes::MULTICAST_UDPCAST:
            case DeployMethodTypes::MULTICAST_UDPCAST_DIRECT:
                $clientJobs = $this->handleMulticastDeployment($input, $image, $trace);
                break;
            case DeployMethodTypes::TORRENT:
                $clientJobs = $this->handleTorrentDeployment($input, $image, $trace);
                break;
        }

        return $clientJobs;
    }

    private function handleUnicastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
    {
        $clientJobs = [];

        foreach ($input->clients as $client) {
            try {
                $inputData = $this->createInputData($input, $image, $client->getEntity());
                $jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::UNICAST, $trace);
                
                if ($jobId) {
                    $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
                }
            } catch (\Exception $e) {
                $this->logger->warning('Error deploying to client (unicast)', [
                    'client_uuid' => $client->getEntity()->getUuid(),
                    'error' => $e->getMessage()
                ]);
                
                if ($input->queue) {
                    $inputData = $this->createInputData($input, $image, $client->getEntity());
                    $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
                }
                
                continue;
            }
        }

        return $clientJobs;
    }

    private function handleMulticastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
    {
        $clientJobs = [];

        foreach ($input->clients as $client) {
            try {
                $inputData = $this->createMulticastInputData($input, $image, $client->getEntity());
                
                try {
                    $this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity());
                } catch (\Exception $e) {
                    $this->logger->warning('Error with OgRepository for client (multicast)', [
                        'client_uuid' => $client->getEntity()->getUuid(),
                        'error' => $e->getMessage()
                    ]);
                    
                    if ($input->queue) {
                        $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
                    }
                    
                    continue;
                }

                $jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::MULTICAST, $trace);
                
                if ($jobId) {
                    $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
                }
            } catch (\Exception $e) {
                $this->logger->warning('Error deploying to client (multicast)', [
                    'client_uuid' => $client->getEntity()->getUuid(),
                    'error' => $e->getMessage()
                ]);
                
                if ($input->queue) {
                    $inputData = $this->createMulticastInputData($input, $image, $client->getEntity());
                    $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
                }
                
                continue;
            }
        }

        return $clientJobs;
    }

    private function handleTorrentDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
    {
        $clientJobs = [];

        foreach ($input->clients as $client) {
            try {
                $inputData = $this->createTorrentInputData($input, $image, $client->getEntity());
                
                try {
                    $response = $this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity(), $this->httpClient);
                    
                    if (is_array($response) && isset($response['code']) && $response['code'] === 500) {
                        throw new \Exception('Error del servidor OgRepository: ' . ($response['error'] ?? 'Error desconocido') . ' - ' . ($response['details'] ?? ''));
                    }
                } catch (\Exception $e) {
                    $this->logger->warning('Error with OgRepository for client (torrent)', [
                        'client_uuid' => $client->getEntity()->getUuid(),
                        'error' => $e->getMessage()
                    ]);
                    
                    if ($input->queue) {
                        $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
                    }
                    
                    continue;
                }

                $jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::TORRENT, $trace);
                
                if ($jobId) {
                    $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
                }
            } catch (\Exception $e) {
                $this->logger->warning('Error deploying to client (torrent)', [
                    'client_uuid' => $client->getEntity()->getUuid(),
                    'error' => $e->getMessage()
                ]);
                
                if ($input->queue) {
                    $inputData = $this->createTorrentInputData($input, $image, $client->getEntity());
                    $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
                }
                
                continue;
            }
        }

        return $clientJobs;
    }

    private function processDeployment($client, DeployImageInput $input, ImageImageRepository $image, array $inputData, string $deployType, ?Trace $trace = null): ?string
    {
        $agentJobId = $this->deployImageOgAgentAction->__invoke($image, $input, $client, $deployType);
        
        if (!$agentJobId) {
            if ($input->queue) {
                if ($trace) {
                    $trace->setStatus(TraceStatus::PENDING);
                    $trace->setJobId(null);
                    $trace->setInput($inputData);
                    $this->entityManager->persist($trace);
                    $this->entityManager->flush();
                } else {
                    $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
                }
            }
            return null;
        }

        if ($trace) {
            $trace->setStatus(TraceStatus::IN_PROGRESS);
            $trace->setJobId($agentJobId);
            $trace->setInput($inputData);
            $this->entityManager->persist($trace);
            $this->entityManager->flush();
        } else {
            $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $agentJobId, $inputData);
        }
        
        return $agentJobId;
    }

    private function createInputData(DeployImageInput $input, ImageImageRepository $image, $client): array
    {
        return [
            'method' => $input->method,
            'client' => $client->getUuid(),
            'image' => $image->getUuid(),
            'imageName' => $image->getName(),
            'numDisk' => (string) $input->diskNumber,
            'numPartition' => (string) $input->partitionNumber,
            'type' => $input->type,
        ];
    }

    private function createMulticastInputData(DeployImageInput $input, ImageImageRepository $image, $client): array
    {
        return array_merge($this->createInputData($input, $image, $client), [
            'mcastIp' => $input->mcastIp,
            'mcastPort' => $input->mcastPort,
            'mcastSpeed' => $input->mcastSpeed,
            'mcastMode' => $input->mcastMode,
        ]);
    }

    private function createTorrentInputData(DeployImageInput $input, ImageImageRepository $image, $client): array
    {
        return array_merge($this->createInputData($input, $image, $client), [
            'p2pMode' => $input->p2pMode,
            'p2pTime' => $input->p2pTime,
        ]);
    }
}
