<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use WriteTextAI\WriteTextAI\Cron\AiModelCron;
use WriteTextAI\WriteTextAI\Helper\ProductDataHelper;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\State;

class TestAiModelCron extends Command
{
    /**
     * @var AiModelCron
     */
    private $aiModelCron;

    /**
     * @var ProductDataHelper
     */
    private $productDataHelper;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var State
     */
    private $state;

    /**
     * Constructor
     *
     * @param AiModelCron $aiModelCron
     * @param ProductDataHelper $productDataHelper
     * @param LoggerInterface $logger
     * @param State $state
     * @param string|null $name
     */
    public function __construct(
        AiModelCron $aiModelCron,
        ProductDataHelper $productDataHelper,
        LoggerInterface $logger,
        State $state,
        ?string $name = null
    ) {
        parent::__construct($name);
        $this->aiModelCron = $aiModelCron;
        $this->productDataHelper = $productDataHelper;
        $this->logger = $logger;
        $this->state = $state;
    }

    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this->setName('writetextai:test-ai-model-cron')
             ->setDescription('Test AI Model Cron without sending to API')
             ->addOption(
                 'store-id',
                 null,
                 InputOption::VALUE_REQUIRED,
                 'Store ID to test'
             );
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
            
            $storeId = (int)($input->getOption('store-id') ?? 1);
            $output->writeln(sprintf('Testing AI Model Cron for store ID: %d', $storeId));

            $totalProducts = $this->productDataHelper->getTotalProductsCount($storeId);
            $output->writeln(sprintf('Total products: %d', $totalProducts));

            if ($totalProducts === 0) {
                $output->writeln('No products found');
                return 0;
            }

            $transformedCategories = $this->aiModelCron->getTransformedCategories($storeId);

            $batchNumber = 0;
            foreach ($this->productDataHelper->getProductsInBatches($storeId) as $batch) {
                $batchNumber++;
                $output->writeln(
                    sprintf(
                        'Processing batch %d/%d (%d products)',
                        $batch['batch_info']['current_page'],
                        $batch['batch_info']['total_pages'],
                        $batch['batch_info']['batch_size']
                    )
                );

                $transformedProducts = $this->aiModelCron->transformProductsData(
                    $batch['products'],
                    $storeId
                );

                $apiData = [
                    'products' => $transformedProducts,
                    'categories' => $transformedCategories
                ];

                $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/kevs.log');
                $kevsLogger = new \Zend_Log();
                $kevsLogger->addWriter($writer);
                $kevsLogger->info(json_encode($apiData, JSON_PRETTY_PRINT));

                $output->writeln(
                    sprintf('Logged batch %d payload to var/log/kevs.log', $batchNumber)
                );
            }

            $output->writeln(sprintf('Logged categories payload to var/log/kevs.log'));
            $output->writeln('Test completed successfully');
            return 0;
        } catch (\Exception $e) {
            $output->writeln(sprintf('Error: %s', $e->getMessage()));
            $this->logger->error(
                'WriteTextAI TestAiModelCron: Error',
                ['exception' => $e]
            );
            return 1;
        }
    }
}
