<?php

namespace AIPT\Api\AutomationJobs\Services;

/**
 * OptionsTranslator
 *
 * Translates job settings into normalized options for tool executors.
 * Keeps executor lean and enforces consistent defaults across tools.
 *
 * @since 2.3.0
 */
class OptionsTranslator {
    private const DEFAULT_OPENAI_MODEL = 'gpt-4.1-mini';

    public function translate(array $settings, string $tool_type): array {
        $tool_type = sanitize_text_field($tool_type);

        $provider = isset($settings['provider']) ? sanitize_text_field($settings['provider']) : 'openai';
        $model    = isset($settings['model']) ? sanitize_text_field($settings['model']) : self::DEFAULT_OPENAI_MODEL;
        $model    = $this->normalizeModel($provider, $model);

        $language       = isset($settings['language']) ? sanitize_text_field($settings['language']) : 'English';
        $writing_style  = isset($settings['writingStyle']) ? sanitize_text_field($settings['writingStyle']) : (isset($settings['writing_style']) ? sanitize_text_field($settings['writing_style']) : 'Professional');
        $contentSettings = isset($settings['contentSettings']) && is_array($settings['contentSettings'])
            ? $settings['contentSettings']
            : [];

        $base = [
            'provider'        => $provider,
            'model'           => $model,
            'language'        => $language,

            'writingStyle'    => $writing_style,
            'writing_style'   => $writing_style,
            'contentSettings' => $contentSettings,
        ];

        if ($tool_type === 'title') {

            $max_length_old = isset($settings['maxTitleLength']) ? (int) $settings['maxTitleLength'] : null;
            $max_length     = isset($settings['maxLength']) ? (int) $settings['maxLength'] : ($max_length_old ?? 80);
            $base['maxTitleLength'] = $max_length; 
            $base['maxLength'] = (string) $max_length; 

            if (isset($settings['keywords'])) {
                $base['keywords'] = sanitize_text_field((string) $settings['keywords']);
            }
            if (isset($settings['titleSources']) && is_array($settings['titleSources'])) {
                $base['titleSources'] = array_values(array_map('sanitize_text_field', $settings['titleSources']));
            }
            if (isset($settings['tone'])) {
                $base['tone'] = sanitize_text_field((string) $settings['tone']);
            }
            if (isset($settings['mode'])) {
                $base['mode'] = sanitize_text_field((string) $settings['mode']);
            }
            if (isset($settings['variantCount'])) {
                $base['variantCount'] = (int) $settings['variantCount'];
            }
            return $base;
        }

        if ($tool_type === 'faq') {
            if (isset($settings['faqCount'])) { $base['faqCount'] = (int) $settings['faqCount']; }
            if (isset($settings['faqFormat'])) { $base['faqFormat'] = sanitize_text_field((string) $settings['faqFormat']); }
            if (isset($settings['faqMode'])) { $base['faqMode'] = sanitize_text_field((string) $settings['faqMode']); }
            if (isset($settings['writeMode'])) { $base['writeMode'] = sanitize_text_field((string) $settings['writeMode']); }
            if (isset($settings['targetField'])) { $base['targetField'] = sanitize_text_field((string) $settings['targetField']); }
            if (isset($settings['faqSources']) && is_array($settings['faqSources'])) {
                $base['faqSources'] = array_values(array_map('sanitize_text_field', $settings['faqSources']));
            }
            if (isset($settings['additionalPrompt'])) { $base['additionalPrompt'] = (string) $settings['additionalPrompt']; }
            return $this->applyFaqPremiumControls($base);
        }

        if ($tool_type === 'seo_meta') {
            foreach (['generateTitle', 'generateDescription', 'generateFocusKeyword', 'optimizeForFocusKeyword', 'generateOgMeta'] as $key) {
                if (isset($settings[$key])) { $base[$key] = (bool) $settings[$key]; }
            }
            foreach (['titleMaxLength', 'descMaxLength', 'variantCount'] as $key) {
                if (isset($settings[$key])) { $base[$key] = (int) $settings[$key]; }
            }
            if (isset($settings['tone'])) { $base['tone'] = sanitize_text_field((string) $settings['tone']); }
            if (isset($settings['sources']) && is_array($settings['sources'])) {
                $base['sources'] = array_values(array_filter(array_map('sanitize_key', $settings['sources'])));
            }
            if (isset($settings['additionalPrompt'])) {
                $base['additionalPrompt'] = (string) $settings['additionalPrompt'];
                $base['additional_prompt'] = (string) $settings['additionalPrompt'];
            }
            if (isset($settings['additional_prompt'])) { $base['additional_prompt'] = (string) $settings['additional_prompt']; }
            return $this->applySeoMetaPremiumControls($base);
        }

        if ($tool_type === 'image_alt') {
            if (isset($settings['includeGallery'])) { $base['includeGallery'] = (bool) $settings['includeGallery']; }
            if (isset($settings['maxLength'])) { $base['maxLength'] = (int) $settings['maxLength']; }
            if (isset($settings['tone'])) { $base['tone'] = sanitize_text_field((string) $settings['tone']); }
            if (isset($settings['enrichWithAttributes'])) { $base['enrichWithAttributes'] = (bool) $settings['enrichWithAttributes']; }
            if (isset($settings['additionalPrompt'])) { $base['additionalPrompt'] = (string) $settings['additionalPrompt']; }
            return $this->applyImageAltPremiumControls($base);
        }

        $base['generateDescription']        = !empty($settings['generateDescription']);
        $base['generateShortDescription']   = !empty($settings['generateShortDescription']);
        $base['generateTags']               = !empty($settings['generateTags']);

        if (array_key_exists('preserve_content_images', $settings)) {
            $base['preserve_content_images'] = (bool) $settings['preserve_content_images'];
        } elseif (array_key_exists('preserveContentImages', $settings)) {
            $base['preserve_content_images'] = (bool) $settings['preserveContentImages'];
        }

        if (isset($settings['content_length_preset'])) {
            $base['content_length_preset'] = sanitize_text_field($settings['content_length_preset']);
        } else {
            $base['content_length_preset'] = 'long';
        }

        if (isset($settings['short_length_preset'])) {
            $base['short_length_preset'] = sanitize_text_field($settings['short_length_preset']);
        } else {
            $base['short_length_preset'] = 'standard';
        }

        if (isset($settings['max_tags_count'])) { $base['max_tags_count'] = (string) $settings['max_tags_count']; }

        if (isset($settings['improveExistingDescription'])) { $base['improveExistingDescription'] = (bool) $settings['improveExistingDescription']; }
        if (isset($settings['keepExistingDescription']))    { $base['keepExistingDescription']    = (bool) $settings['keepExistingDescription']; }
        if (isset($settings['additionalTagsCount']))        { $base['additionalTagsCount']        = (int)  $settings['additionalTagsCount']; }

        if (isset($settings['existingDescriptionPosition'])) {
            $pos = in_array($settings['existingDescriptionPosition'], ['before','after'], true)
                ? $settings['existingDescriptionPosition']
                : 'after';
            $base['existingDescriptionPosition'] = $pos;
        }
        if (isset($settings['beforeContentText'])) {
            $base['beforeContentText'] = sanitize_text_field((string) $settings['beforeContentText']);
        }
        if (isset($settings['afterContentText'])) {
            $base['afterContentText'] = sanitize_text_field((string) $settings['afterContentText']);
        }

        if (isset($settings['seo'])) {
            $base['seo'] = is_array($settings['seo']) ? $settings['seo'] : [];
        }

        if (isset($settings['prompts']) && is_array($settings['prompts'])) {
            $base['prompts'] = $settings['prompts'];
        } else {

            $short_system = $settings['short_system_prompt'] ?? $settings['standard_short_system_prompt'] ?? null;
            $short_user   = $settings['short_user_prompt'] ?? $settings['standard_short_user_prompt'] ?? null;
            $full_system  = $settings['full_system_prompt'] ?? $settings['standard_full_system_prompt'] ?? null;
            $full_user    = $settings['full_user_prompt'] ?? $settings['standard_full_user_prompt'] ?? null;

            if ($short_system !== null || $short_user !== null || $full_system !== null || $full_user !== null) {
                $base['prompts'] = [
                    'short' => [
                        'system_prompt' => (string) ($short_system ?? ''),
                        'user_prompt'   => (string) ($short_user ?? ''),
                    ],
                    'full'  => [
                        'system_prompt' => (string) ($full_system ?? ''),
                        'user_prompt'   => (string) ($full_user ?? ''),
                    ],
                ];
            }
        }

        return $base;
    }

    private function applyFaqPremiumControls(array $options): array {
        $free_defaults = [
            'faqMode'     => 'both',
            'writeMode'   => 'append',
            'targetField' => 'post_content',
            'faqSources'  => ['product_description'],
        ];

		$controlled = array_merge($options, $free_defaults);
        unset($controlled['additionalPrompt']);

        return apply_filters('aipt_faq_validate_options', $controlled, $options);
    }

    private function applySeoMetaPremiumControls(array $options): array {
        $free_defaults = [
            'tone'                    => 'Professional',
            'titleMaxLength'          => 60,
            'descMaxLength'           => 160,
            'generateFocusKeyword'    => false,
            'optimizeForFocusKeyword' => false,
            'generateOgMeta'          => false,
            'variantCount'            => 2,
        ];

		$controlled = array_merge($options, $free_defaults);
        unset($controlled['additionalPrompt'], $controlled['additional_prompt']);
        $controlled = apply_filters('aipt_seo_meta_validate_options', $controlled, $options);

        $allowed_sources = [
            'product_name',
            'product_brand',
            'product_description',
            'short_description',
            'product_categories',
            'product_tags',
            'product_attributes',
            'product_sku',
            'product_price',
        ];

        if (isset($controlled['sources']) && is_array($controlled['sources'])) {
            $controlled['sources'] = array_values(array_intersect($controlled['sources'], $allowed_sources));
            if (empty($controlled['sources'])) {
                $controlled['sources'] = ['product_name', 'product_description', 'product_categories'];
            }
        } else {
            $controlled['sources'] = ['product_name', 'product_description', 'product_categories'];
        }

        return $controlled;
    }

    private function applyImageAltPremiumControls(array $options): array {
        $free_defaults = [
            'includeGallery'       => false,
            'tone'                 => 'descriptive',
            'enrichWithAttributes' => false,
            'additionalPrompt'     => '',
        ];

		$controlled = array_merge($options, $free_defaults);

        return apply_filters('aipt_image_alt_validate_options', $controlled, $options);
    }

    /**
     * Normalize model selections for backward compatibility with deprecated entries.
     *
     * @param string $provider Selected AI provider
     * @param string $model Requested model
     * @return string Supported model identifier
     */
    private function normalizeModel(string $provider, string $model): string {
        $model = trim($model);

        if ($provider === 'gemini') {
            $valid = [
                'gemini-3.5-flash',
                'gemini-3.1-pro-preview',
                'gemini-3.1-flash-lite',
                'gemini-3-flash-preview',
                'gemini-2.5-pro',
                'gemini-2.5-flash',
                'gemini-2.5-flash-lite',
            ];

            return in_array($model, $valid, true) ? $model : 'gemini-2.5-flash';
        }

        if ($provider === 'claude') {
            $valid = [
                'claude-opus-4-8',
                'claude-opus-4-7',
                'claude-opus-4-6',
                'claude-sonnet-4-6',
                'claude-opus-4-5-20251101',
                'claude-sonnet-4-5-20250929',
                'claude-haiku-4-5-20251001',
                'claude-opus-4-1-20250805',
            ];

            return in_array($model, $valid, true) ? $model : 'claude-sonnet-4-6';
        }

        if ($provider === 'openrouter') {
            return $model !== '' ? $model : 'openrouter/free';
        }

        $valid = [
            'gpt-5.5',
            'gpt-5.5-pro',
            'gpt-5.4',
            'gpt-5.4-mini',
            'gpt-5.4-nano',
            'gpt-4.1',
            'gpt-4.1-mini',
            'gpt-4.1-nano',
            'o4-mini',
            'o3-pro',
            'o3',
        ];

        if ($model === '') {
            return self::DEFAULT_OPENAI_MODEL;
        }

        return in_array($model, $valid, true) ? $model : self::DEFAULT_OPENAI_MODEL;
    }
}
