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

namespace WriteTextAI\WriteTextAI\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;
use WriteTextAI\WriteTextAI\Model\Api\AIModels as AIModelsApi;

/**
 * ViewModel for AI model options
 */
class AiModels implements ArgumentInterface
{
    /**
     * @var AIModelsApi
     */
    protected $aiModelsApi;

    /**
     * @var array
     */
    protected $aiModels = [];

    /**
     * Constructor
     *
     * @param AIModelsApi $aiModelsApi
     */
    public function __construct(
        AIModelsApi $aiModelsApi
    ) {
        $this->aiModelsApi = $aiModelsApi;
    }

    /**
     * Get available AI models (excluding default "No ai model" option)
     *
     * @return array
     */
    public function getAvailableAiModels(): array
    {
        if (!empty($this->aiModels)) {
            return $this->aiModels;
        }

        try {
            $aiModels = $this->aiModelsApi->getCurrentAIModelSettings();
            $aiModels = is_array($aiModels) ? $aiModels : [];
            $this->aiModels = $aiModels;
            return $aiModels;
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * Get all AI models including "No ai model" option when needed
     *
     * @return array
     */
    public function getAiModels(): array
    {
        $availableModels = $this->getAvailableAiModels();
        
        // If no models are available, return only "No ai model" option
        if (empty($availableModels)) {
            return [
                [
                    'id' => '',
                    'name' => __('No brand voice'),
                    'selected' => true
                ]
            ];
        } else {
            array_unshift($availableModels, [
                'id' => '',
                'name' => __('Select...'),
                'selected' => true
            ]);
        }
        
        // If models are available, return only the available models (no "No ai model" option)
        return $availableModels;
    }

    /**
     * Get AI models as JSON for JavaScript use
     *
     * @return string
     */
    public function getAiModelsJson(): string
    {
        return json_encode($this->getAiModels());
    }

    /**
     * Check if AI models are available
     *
     * @return bool
     */
    public function hasAiModels(): bool
    {
        $availableModels = $this->getAvailableAiModels();
        return count($availableModels) > 0;
    }
}
