<?php

namespace HaoZiTeam\AIPost\Service\Features;

defined('ABSPATH') || exit;

class EditorGenerateUI
{
    private static function normalize_provider(string $provider): string
    {
        $provider = trim((string)$provider);
        if ($provider === '') {
            $provider = 'custom';
        }
        if ($provider === 'openai') {
            // settings 中 openai/custom 共享 openai-accounts
            return 'custom';
        }
        return $provider;
    }

    private static function get_provider_model_catalog(string $provider): array
    {
        $provider = self::normalize_provider($provider);

        if ($provider === 'openai' || $provider === 'custom') {
            return [
                'gpt-4o-mini',
                'gpt-4o-mini-2024-07-18',
                'gpt-4o',
                'gpt-4o-2024-05-13',
                'gpt-3.5-turbo-0613',
            ];
        }
        if ($provider === 'deepseek') {
            return [
                'deepseek-chat',
                'deepseek-reasoner',
            ];
        }
        if ($provider === 'doubao') {
            return [
                'doubao-seed-2-0-mini-260215',
                'doubao-1-5-lite-32k-250115',
                'doubao-1-5-pro-32k-250115',
                'doubao-seed-2-0-pro-260215',
                'doubao-seed-2-0-lite-260215',
                'doubao-seed-2-0-code-preview-260215',
                'doubao-seed-1-8-251228',
                'doubao-seed-1-6-flash-250828',
                'doubao-seed-1-6-vision-250815',
                'doubao-seed-1-6-lite-251015',
                'glm-4-7-251222',
                'deepseek-v3-2-251201',
                'deepseek-v3-1-terminus',
                'deepseek-r1-250528',
                'deepseek-v3-250324',
            ];
        }
        if ($provider === 'bai-lian') {
            return [
                'qwen-max',
                'qwen-max-latest',
                'qwen-max-2024-09-19',
                'qwen-plus',
                'qwen-plus-latest',
                'qwen-plus-2025-01-25',
                'qwen-turbo',
                'qwen-turbo-latest',
                'qwen-long',
                'qwen-long-latest',
            ];
        }
        if ($provider === 'wenxin') {
            try {
                return array_keys(WenXinModelCatalog::optionsForSelect());
            } catch (\Throwable $e) {
                return [];
            }
        }

        if ($provider === 'zhipu') {
            return [
                'glm-4.7-flashx',
                'glm-4.7-flash',
                'glm-4-flash-250414',
                'glm-4.7',
                'glm-5',
            ];
        }

        if ($provider === 'spark') {
            return [
                'x1',
                'spark-x',
                'lite',
                'spark-pro',
                'spark-max',
                'custom',
            ];
        }

        if ($provider === 'moonshot') {
            return [
                'moonshot-v1-8k',
                'moonshot-v1-32k',
                'moonshot-v1-128k',
                'kimi-k2.5',
                'kimi-k2-0905-preview',
                'kimi-k2-0711-preview',
                'kimi-k2-turbo-preview',
                'kimi-k2-thinking',
                'kimi-k2-thinking-turbo',
            ];
        }

        return [];
    }

    private static function provider_has_credentials(array $settings, string $provider): bool
    {
        $provider = self::normalize_provider($provider);

        // OpenAI/Custom: openai-accounts 或安全存储
        if ($provider === 'custom') {
            $accounts = $settings['openai-accounts'] ?? [];
            if (is_array($accounts)) {
                foreach ($accounts as $acc) {
                    if (!is_array($acc)) {
                        continue;
                    }
                    $k = trim((string)($acc['account-secret-key'] ?? ''));
                    if ($k !== '') {
                        return true;
                    }
                }
            }
            try {
                $k1 = SecureSettings::get('openai_key');
                $k2 = SecureSettings::get('custom_key');
                if ((is_string($k1) && trim($k1) !== '') || (is_string($k2) && trim($k2) !== '')) {
                    return true;
                }
            } catch (\Throwable $e) {
            }
            return false;
        }

        if ($provider === 'moonshot') {
            $accounts = $settings['moonshot-accounts'] ?? [];
            if (is_array($accounts)) {
                foreach ($accounts as $acc) {
                    if (!is_array($acc)) {
                        continue;
                    }
                    $k = trim((string)($acc['account-secret-key'] ?? ''));
                    if ($k !== '') {
                        return true;
                    }
                }
            }
            try {
                $k = SecureSettings::get('moonshot_key');
                if (is_string($k) && trim($k) !== '') {
                    return true;
                }
            } catch (\Throwable $e) {
            }
            return false;
        }

        if ($provider === 'deepseek') {
            $accounts = $settings['deepseek-accounts'] ?? [];
            if (is_array($accounts)) {
                foreach ($accounts as $acc) {
                    if (!is_array($acc)) {
                        continue;
                    }
                    $k = trim((string)($acc['account-secret-key'] ?? ''));
                    if ($k !== '') {
                        return true;
                    }
                }
            }
            try {
                $k = SecureSettings::get('deepseek_key');
                if (is_string($k) && trim($k) !== '') {
                    return true;
                }
            } catch (\Throwable $e) {
            }
            return false;
        }

        if ($provider === 'doubao') {
            $accounts = $settings['doubao-accounts'] ?? [];
            if (is_array($accounts)) {
                foreach ($accounts as $acc) {
                    if (!is_array($acc)) {
                        continue;
                    }
                    $k = trim((string)($acc['account-secret-key'] ?? ''));
                    if ($k !== '') {
                        return true;
                    }
                }
            }
            try {
                $k = SecureSettings::get('doubao_key');
                if (is_string($k) && trim($k) !== '') {
                    return true;
                }
            } catch (\Throwable $e) {
            }
            return false;
        }

        if ($provider === 'bai-lian') {
            $accounts = $settings['bai-lian-accounts'] ?? [];
            if (is_array($accounts)) {
                foreach ($accounts as $acc) {
                    if (!is_array($acc)) {
                        continue;
                    }
                    $k = trim((string)($acc['account-secret-key'] ?? ''));
                    if ($k !== '') {
                        return true;
                    }
                }
            }
            try {
                $k = SecureSettings::get('bai_lian_key');
                if (is_string($k) && trim($k) !== '') {
                    return true;
                }
            } catch (\Throwable $e) {
            }
            return false;
        }

        if ($provider === 'wenxin') {
            $accounts = $settings['wenxin-accounts'] ?? [];
            if (!is_array($accounts)) {
                return false;
            }
            foreach ($accounts as $acc) {
                if (!is_array($acc)) {
                    continue;
                }
                $ak = trim((string)($acc['api-key'] ?? ''));
                $sk = trim((string)($acc['secret-key'] ?? ''));
                if ($ak !== '' && $sk !== '') {
                    return true;
                }
            }
            return false;
        }

        if ($provider === 'zhipu') {
            $accounts = $settings['zhipu-accounts'] ?? [];
            if (is_array($accounts)) {
                foreach ($accounts as $acc) {
                    if (!is_array($acc)) {
                        continue;
                    }
                    $k = trim((string)($acc['account-secret-key'] ?? ''));
                    if ($k !== '') {
                        return true;
                    }
                }
            }
            try {
                $k = SecureSettings::get('zhipu_key');
                if (is_string($k) && trim($k) !== '') {
                    return true;
                }
            } catch (\Throwable $e) {
            }
            return false;
        }

        if ($provider === 'spark') {
            $accounts = $settings['spark-accounts'] ?? [];
            if (is_array($accounts)) {
                foreach ($accounts as $acc) {
                    if (!is_array($acc)) {
                        continue;
                    }
                    $kOld = trim((string)($acc['account-secret-key'] ?? ''));
                    $kV2 = trim((string)($acc['account-secret-key-v2'] ?? ''));
                    $kV1 = trim((string)($acc['account-secret-key-v1'] ?? ''));
                    $kPro = trim((string)($acc['account-secret-key-pro'] ?? ''));
                    $kMax = trim((string)($acc['account-secret-key-max'] ?? ''));
                    if ($kOld !== '' || $kV2 !== '' || $kV1 !== '' || $kPro !== '' || $kMax !== '') {
                        return true;
                    }
                }
            }
            try {
                $kOld = SecureSettings::get('spark_key');
                $kV2 = SecureSettings::get('spark_v2_key');
                $kV1 = SecureSettings::get('spark_v1_key');
                $kPro = SecureSettings::get('spark_pro_key');
                $kMax = SecureSettings::get('spark_max_key');
                if (
                    (is_string($kOld) && trim($kOld) !== '')
                    || (is_string($kV2) && trim($kV2) !== '')
                    || (is_string($kV1) && trim($kV1) !== '')
                    || (is_string($kPro) && trim($kPro) !== '')
                    || (is_string($kMax) && trim($kMax) !== '')
                ) {
                    return true;
                }
            } catch (\Throwable $e) {
            }
            return false;
        }

        return false;
    }

    public static function build_model_options(): array
    {
        $settings = get_option('ai-post', []);
        if (!is_array($settings)) {
            $settings = [];
        }

        // 聚合所有“已配置秘钥/账号”的 provider
        $allProviders = ['custom', 'zhipu', 'spark', 'deepseek', 'moonshot', 'doubao', 'bai-lian', 'wenxin'];
        $enabledProviders = [];
        foreach ($allProviders as $p) {
            if (self::provider_has_credentials($settings, $p)) {
                $enabledProviders[] = $p;
            }
        }

        // 如果一个都没配置，回退到当前 api-server-type（保持旧行为）
        if (empty($enabledProviders)) {
            $cur = isset($settings['api-server-type']) ? trim((string)$settings['api-server-type']) : '';
            $cur = self::normalize_provider($cur);
            $enabledProviders = [$cur ?: 'custom'];
        }

        $options = [
            ['value' => '', 'label' => '账号默认'],
        ];
        $allow = [];
        $defaultModel = '';

        foreach ($enabledProviders as $provider) {
            $provider = self::normalize_provider($provider);

            $decorateLabel = function (string $p, string $m): string {
                $pLabel = $p;
                if ($p === 'custom') {
                    $pLabel = 'openai';
                } elseif ($p === 'deepseek') {
                    $pLabel = 'deepseek';
                } elseif ($p === 'spark') {
                    $pLabel = '星火';
                } elseif ($p === 'zhipu') {
                    $pLabel = '智谱';
                } elseif ($p === 'moonshot') {
                    $pLabel = '月之';
                } elseif ($p === 'doubao') {
                    $pLabel = '豆包';
                } elseif ($p === 'bai-lian') {
                    $pLabel = '百炼';
                } elseif ($p === 'wenxin') {
                    $pLabel = '文心';
                }

                if ($p === 'zhipu' && $m === 'glm-4.7-flash') {
                    return $pLabel . ' / ' . $m . '（免费）';
                }
                return $pLabel . ' / ' . $m;
            };

            // 内置目录模型
            $catalog = self::get_provider_model_catalog($provider);
            foreach ($catalog as $m) {
                $m = trim((string)$m);
                if ($m === '') {
                    continue;
                }
                $val = $provider . '::' . $m;
                $options[] = ['value' => $val, 'label' => $decorateLabel($provider, $m)];
                $allow[] = $val;
            }

            // 账号自定义模型名（custom-model-name）也加入
            $accountsKeyMap = [
                'deepseek' => 'deepseek-accounts',
                'moonshot' => 'moonshot-accounts',
                'doubao' => 'doubao-accounts',
                'bai-lian' => 'bai-lian-accounts',
                'wenxin' => 'wenxin-accounts',
                'zhipu' => 'zhipu-accounts',
                'spark' => 'spark-accounts',
                'custom' => 'openai-accounts',
            ];
            $accountsKey = $accountsKeyMap[$provider] ?? '';
            $accounts = $accountsKey !== '' ? ($settings[$accountsKey] ?? []) : [];
            if (!is_array($accounts)) {
                $accounts = [];
            }
            foreach ($accounts as $acc) {
                if (!is_array($acc)) {
                    continue;
                }
                $customName = trim((string)($acc['custom-model-name'] ?? ''));
                if ($customName !== '') {
                    $val = $provider . '::' . $customName;
                    $options[] = ['value' => $val, 'label' => $decorateLabel($provider, $customName)];
                    $allow[] = $val;
                }

                // 默认值：优先取第一个账号的当前选择（含 custom）
                if ($defaultModel === '') {
                    $sel = trim((string)($acc['model-selection'] ?? ''));
                    $resolved = $sel === 'custom' ? $customName : $sel;
                    $resolved = trim((string)$resolved);
                    if ($resolved !== '') {
                        $defaultModel = $provider . '::' . $resolved;
                    }
                }
            }
        }

        // 去重
        $seen = [];
        $uniqueOptions = [];
        foreach ($options as $opt) {
            $v = (string)($opt['value'] ?? '');
            if ($v !== '' && isset($seen[$v])) {
                continue;
            }
            if ($v !== '') {
                $seen[$v] = 1;
            }
            $uniqueOptions[] = $opt;
        }
        $options = $uniqueOptions;
        $allow = array_values(array_unique(array_filter(array_map('trim', $allow))));

        return [
            'provider' => 'multi',
            'default' => $defaultModel,
            'options' => $options,
            'allow' => $allow,
            'enabled_providers' => $enabledProviders,
        ];
    }

    /**
     * 获取已配置秘钥的文生图 provider 列表
     * @return array [ ['value'=>'zhipu','label'=>'智谱'], ... ]
     */
    public static function get_t2i_providers(): array
    {
        $settings = get_option('ai-post', []);
        if (!is_array($settings)) {
            return [];
        }
        $map = [
            'zhipu-accounts'    => ['value' => 'zhipu',  'label' => '智谱'],
            'doubao-accounts'   => ['value' => 'doubao', 'label' => '豆包'],
            'bai-lian-accounts' => ['value' => 'aliyun', 'label' => '阿里百炼'],
        ];
        $providers = [];
        foreach ($map as $acct_key => $info) {
            $accts = $settings[$acct_key] ?? [];
            if (is_array($accts)) {
                foreach ($accts as $acc) {
                    if (is_array($acc) && trim((string)($acc['account-secret-key'] ?? '')) !== '') {
                        $providers[] = $info;
                        break;
                    }
                }
            }
        }
        return $providers;
    }

    /**
     * 检查是否至少配置了一个文生图 provider 的 API Key
     */
    public static function has_t2i_api_key(): bool
    {
        return !empty(self::get_t2i_providers());
    }

    public static function register(): void
    {
        if (!is_admin()) {
            return;
        }
        add_action('add_meta_boxes', [__CLASS__, 'add_metabox']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_classic_assets']);
        add_action('enqueue_block_editor_assets', [__CLASS__, 'enqueue_gutenberg_assets']);
    }

    public static function add_metabox(): void
    {
        $screens = ['post', 'page'];
        foreach ($screens as $screen) {
            add_meta_box(
                'aipost_editor_generate_box',
                'AI 生成内容',
                [__CLASS__, 'render_metabox'],
                $screen,
                'normal',
                'high'
            );
        }
    }

    public static function render_metabox(\WP_Post $post): void
    {
        $nonce = wp_create_nonce('wp_rest');
        echo '<div id="aipost-editor-generate-classic" data-post-id="' . esc_attr((string)$post->ID) . '" data-rest-nonce="' . esc_attr($nonce) . '"></div>';
    }

    public static function enqueue_gutenberg_assets(): void
    {
        $src = plugins_url('assets/js/editor-ai-generate-gutenberg.js', defined('HaoZiTeam\\AIPost\\PLUGIN_FILE') ? \HaoZiTeam\AIPost\PLUGIN_FILE : (defined('PLUGIN_FILE') ? PLUGIN_FILE : __FILE__));
        $ver = defined('HaoZiTeam\\AIPost\\VERSION') ? \HaoZiTeam\AIPost\VERSION : (defined('HAOZI_AIPOST_VERSION') ? HAOZI_AIPOST_VERSION : '1.0.0');
        wp_enqueue_script(
            'aipost-editor-generate-gutenberg',
            $src,
            ['wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-api-fetch'],
            $ver,
            true
        );

        $models = self::build_model_options();
        $t2iProviders = self::get_t2i_providers();
        $inline = 'window.AIPostEditorGenerate = window.AIPostEditorGenerate || {};' .
            'window.AIPostEditorGenerate.restNonce = ' . json_encode(wp_create_nonce('wp_rest')) . ';' .
            'window.AIPostEditorGenerate.models = ' . json_encode($models['options']) . ';' .
            'window.AIPostEditorGenerate.defaultModel = ' . json_encode($models['default']) . ';' .
            'window.AIPostEditorGenerate.provider = ' . json_encode($models['provider']) . ';' .
            'window.AIPostEditorGenerate.t2iProviders = ' . json_encode($t2iProviders) . ';';
        wp_add_inline_script('aipost-editor-generate-gutenberg', $inline, 'before');
    }

    public static function enqueue_classic_assets(string $hook): void
    {
        if (!in_array($hook, ['post.php', 'post-new.php'], true)) {
            return;
        }

        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        $post_type = $screen && isset($screen->post_type) ? (string)$screen->post_type : '';
        if (!in_array($post_type, ['post', 'page'], true)) {
            return;
        }

        $src = plugins_url('assets/js/editor-ai-generate-classic.js', defined('HaoZiTeam\\AIPost\\PLUGIN_FILE') ? \HaoZiTeam\AIPost\PLUGIN_FILE : (defined('PLUGIN_FILE') ? PLUGIN_FILE : __FILE__));
        $ver = defined('HaoZiTeam\\AIPost\\VERSION') ? \HaoZiTeam\AIPost\VERSION : (defined('HAOZI_AIPOST_VERSION') ? HAOZI_AIPOST_VERSION : '1.0.0');

        wp_enqueue_script(
            'aipost-editor-generate-classic',
            $src,
            ['jquery'],
            $ver,
            true
        );

        $models = self::build_model_options();

        wp_localize_script('aipost-editor-generate-classic', 'AIPostEditorGenerateClassic', [
            'restNonce' => wp_create_nonce('wp_rest'),
            'restUrl' => esc_url_raw(rest_url()),
            'confirmOverwrite' => '将覆盖当前正文/摘要/标签/SEO描述，是否继续？',
            'models' => $models['options'],
            'defaultModel' => $models['default'],
            'provider' => $models['provider'],
            't2iProviders' => self::get_t2i_providers(),
        ]);
    }
}

EditorGenerateUI::register();
