<?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;
        }

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

        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;
    }

    /**
     * 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.1-pro-preview',
                'gemini-3-flash-preview',
                'gemini-3.1-flash-lite-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-6',
                'claude-sonnet-4-6',
                'claude-opus-4-5-20251101',
                'claude-sonnet-4-5-20250929',
                'claude-haiku-4-5-20251001',
                'claude-sonnet-4-20250514',
            ];

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

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

        $valid = [
            'gpt-5.4',
            'gpt-5.4-mini',
            'gpt-5.4-nano',
            'gpt-5.2',
            'gpt-5.2-pro',
            'gpt-5-mini',
            'gpt-5-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;
    }
}

