<?php

namespace XZD\AI\V5\Admin;

use XZD\AI\V5\Tools\ToolRegistry;

/**
 * 文章编辑页AI助手 — 侧边栏显示AI工具状态面板和操作按钮，与处理标记系统联动
 */
class PostEditorAI
{
    private static ?self $instance = null;

    /** 在编辑器中显示的工具ID列表 */
    private const EDITOR_TOOLS = [
        'generate_summary'   => ['label' => 'AI摘要',   'icon' => '📄'],
        'generate_tags'      => ['label' => 'AI标签',   'icon' => '🏷️'],
        'generate_seo'       => ['label' => 'SEO优化',   'icon' => '🔍'],
        'generate_cover'     => ['label' => '封面图',   'icon' => '🎨'],
        'generate_alt'       => ['label' => 'ALT文字',  'icon' => '🖼️'],
        'build_autolink'     => ['label' => '内链构建',  'icon' => '🔗'],
        'polish_content'     => ['label' => '内容润色',  'icon' => '✨'],
        'score_quality'      => ['label' => '质量评分',  'icon' => '📊'],
    ];

    public static function instance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function init(): void
    {
        add_action('add_meta_boxes', [$this, 'addMetabox']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
        add_action('init', [$this, 'registerMeta']);
    }

    /**
     * 注册处理标记meta字段为REST API可见，Gutenberg面板才能读取
     */
    public function registerMeta(): void
    {
        $toolIds = array_keys(self::EDITOR_TOOLS);
        // 补充编辑器面板不显示但需要REST可见的工具
        $extraIds = ['translate_content', 'rewrite_content', 'expand_content'];
        $allIds = array_merge($toolIds, $extraIds);

        foreach ($allIds as $toolId) {
            register_post_meta('post', '_xzd_ai_processed_' . $toolId, [
                'show_in_rest'  => true,
                'single'        => true,
                'type'          => 'string',
                'auth_callback' => function () {
                    return current_user_can('edit_posts');
                },
            ]);
        }

        // 工具结果 meta（前端侧边栏读取）
        $resultMetas = [
            '_xzd_ai_summary'          => 'string',
            '_xzd_ai_tags_count'       => 'integer',
            '_xzd_ai_seo_title'        => 'string',
            '_xzd_ai_seo_keywords'     => 'string',
            '_xzd_ai_seo_description'  => 'string',
            '_xzd_ai_quality_score'    => 'string',
            '_xzd_ai_autolinks'        => 'string',
            '_xzd_ai_cover_prompt'     => 'string',
            '_xzd_ai_polished'         => 'string',
            '_xzd_ai_rewritten'        => 'string',
        ];
        foreach ($resultMetas as $key => $type) {
            register_post_meta('post', $key, [
                'show_in_rest'  => true,
                'single'        => true,
                'type'          => $type,
                'auth_callback' => function () {
                    return current_user_can('edit_posts');
                },
            ]);
        }

        // AI生成标记
        register_post_meta('post', '_xzd_ai_generated', [
            'show_in_rest'  => true,
            'single'        => true,
            'type'          => 'boolean',
            'auth_callback' => function () {
                return current_user_can('edit_posts');
            },
        ]);

        // AI写作标记
        register_post_meta('post', '_xzd_ai_written', [
            'show_in_rest'  => true,
            'single'        => true,
            'type'          => 'string',
            'auth_callback' => function () {
                return current_user_can('edit_posts');
            },
        ]);

        // 人工审核标记
        register_post_meta('post', '_xzd_ai_reviewed', [
            'show_in_rest'  => true,
            'single'        => true,
            'type'          => 'boolean',
            'default'       => false,
            'auth_callback' => function () {
                return current_user_can('edit_posts');
            },
        ]);
    }

    public function addMetabox(): void
    {
        // Gutenberg模式下由 gutenberg-ai-panel.js 的 PluginDocumentSettingPanel 渲染，避免双重面板
        $screen = get_current_screen();
        if ($screen && $screen->is_block_editor()) {
            return;
        }

        add_meta_box(
            'xzd-ai-editor-tools',
            '小栈AI · 文章处理',
            [$this, 'renderMetabox'],
            'post',
            'side',
            'default'
        );
    }

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

        $screen = get_current_screen();
        $isGutenberg = $screen && $screen->is_block_editor();

        // 通用 CSS
        wp_enqueue_style('xzd-editor-ai', XZD_AI_URL . 'assets/standalone/post-editor-ai.css', [], XZD_AI_VERSION);

        $jsConfig = [
            'restUrl' => rest_url(XZD_AI_REST_NAMESPACE),
            'nonce'   => wp_create_nonce('wp_rest'),
            'postId'  => get_the_ID(),
            'tools'   => self::EDITOR_TOOLS,
            // 内链样式配置从全局键读取，供编辑器前端使用
            'autolink' => [
                'link_color'       => \XZD\AI\V5\Core\Config::instance()->get('autolink_link_color', '#2F6BFF'),
                'link_weight'      => \XZD\AI\V5\Core\Config::instance()->get('autolink_link_weight', '500'),
                'text_decoration'  => \XZD\AI\V5\Core\Config::instance()->get('autolink_text_decoration', 'underline'),
            ],
            'i18n'    => [
                'processing'    => '处理中...',
                'success'       => '完成',
                'failed'        => '失败',
                'notProcessed'  => '未处理',
                'confirmRedo'   => '确定要重新处理吗？将覆盖已有结果。',
                'confirmAll'    => '确定要一键处理所有项目吗？',
                'confirmClear'  => '确定要清除所有标记并全部重新处理吗？这将覆盖所有已有结果。',
            ],
        ];

        if ($isGutenberg) {
            // Gutenberg 智能面板 — 使用 @wordpress/editor（WP 6.6+）
            wp_enqueue_script(
                'xzd-gutenberg-ai-panel',
                XZD_AI_URL . 'assets/standalone/gutenberg-ai-panel.js',
                ['wp-plugins', 'wp-editor', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n', 'wp-blocks', 'wp-block-editor', 'wp-hooks'],
                XZD_AI_VERSION,
                true
            );
            wp_localize_script('xzd-gutenberg-ai-panel', 'xzdEditorAI', $jsConfig);
        } else {
            // 经典编辑器 vanilla JS 增强
            wp_enqueue_script('xzd-editor-ai', XZD_AI_URL . 'assets/standalone/post-editor-ai.js', [], XZD_AI_VERSION, true);
            wp_localize_script('xzd-editor-ai', 'xzdEditorAI', $jsConfig);
        }
    }

    public function renderMetabox(\WP_Post $post): void
    {
        $postId = $post->ID;
        ?>
        <div id="xzd-editor-ai-panel">
            <?php foreach (self::EDITOR_TOOLS as $toolId => $info): ?>
            <div class="xzd-ai-row" data-tool="<?php echo esc_attr($toolId); ?>">
                <span class="xzd-ai-icon"><?php echo esc_html($info['icon']); ?></span>
                <span class="xzd-ai-label"><?php echo esc_html($info['label']); ?></span>
                <span class="xzd-ai-status" data-tool-status="<?php echo esc_attr($toolId); ?>">
                    <?php echo $this->getToolStatusText($postId, $toolId); ?>
                </span>
                <button type="button"
                    class="xzd-ai-btn button button-small"
                    data-tool-btn="<?php echo esc_attr($toolId); ?>"
                    data-post="<?php echo (int)$postId; ?>">
                    <?php echo $this->getToolBtnText($postId, $toolId); ?>
                </button>
            </div>
            <?php endforeach; ?>

            <div class="xzd-ai-divider"></div>

            <div class="xzd-ai-quick-actions">
                <button type="button" class="button button-primary button-small" id="xzd-ai-fill-empty"
                    data-post="<?php echo (int)$postId; ?>">
                    仅填充空白
                </button>
                <button type="button" class="button button-small" id="xzd-ai-process-all"
                    data-post="<?php echo (int)$postId; ?>">
                    一键全处理
                </button>
                <button type="button" class="button button-small button-link-delete" id="xzd-ai-redo-all"
                    data-post="<?php echo (int)$postId; ?>">
                    全部覆盖重做
                </button>
            </div>

            <div class="xzd-ai-log" id="xzd-ai-log" style="display:none;"></div>

            <?php $backup = get_post_meta($postId, '_xzd_ai_content_backup', true); ?>
            <?php if (!empty($backup)): ?>
            <div class="xzd-ai-divider"></div>
            <button type="button" class="button button-small button-link-delete" id="xzd-ai-restore-backup"
                data-post="<?php echo (int)$postId; ?>" style="width:100%">
                恢复AI修改前原文
            </button>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * 获取工具处理状态文字
     */
    private function getToolStatusText(int $postId, string $toolId): string
    {
        // 摘要读 _xzd_ai_summary
        if ($toolId === 'generate_summary') {
            $summary = get_post_meta($postId, '_xzd_ai_summary', true);
            if (!empty($summary)) {
                $len = mb_strlen($summary);
                return "<span class='xzd-status-done'>已生成({$len}字)</span>";
            }
            return "<span class='xzd-status-none'>未生成</span>";
        }

        // 标签读 taxonomy
        if ($toolId === 'generate_tags') {
            $tags = wp_get_post_tags($postId);
            if (!empty($tags)) {
                $count = count($tags);
                return "<span class='xzd-status-done'>已有{$count}个标签</span>";
            }
            $marker = get_post_meta($postId, '_xzd_ai_processed_' . $toolId, true);
            if (!empty($marker) && ($marker['status'] ?? '') === 'completed') {
                return "<span class='xzd-status-done'>已处理</span>";
            }
            return "<span class='xzd-status-none'>未处理</span>";
        }

        // 通用：读 _xzd_ai_processed_{tool_id}
        $marker = get_post_meta($postId, '_xzd_ai_processed_' . $toolId, true);
        if (!empty($marker) && ($marker['status'] ?? '') === 'completed') {
            $summary = $marker['summary'] ?? '';
            return "<span class='xzd-status-done'>已处理</span>";
        }

        return "<span class='xzd-status-none'>未处理</span>";
    }

    /**
     * 获取工具按钮文字
     */
    private function getToolBtnText(int $postId, string $toolId): string
    {
        if ($toolId === 'generate_summary') {
            $summary = get_post_meta($postId, '_xzd_ai_summary', true);
            return !empty($summary) ? '重新生成' : '生成';
        }
        if ($toolId === 'generate_tags') {
            $tags = wp_get_post_tags($postId);
            return !empty($tags) ? '重新生成' : '生成';
        }
        $marker = get_post_meta($postId, '_xzd_ai_processed_' . $toolId, true);
        if (!empty($marker) && ($marker['status'] ?? '') === 'completed') {
            return '重新处理';
        }
        return '处理';
    }
}
