<?php

namespace XZD\AI\V5\REST\Controllers;

use XZD\AI\V5\REST\BaseController;
use XZD\AI\V5\SEO\TagGovernance;
use XZD\AI\V5\Core\Logger;
use WP_REST_Request;
use WP_REST_Response;

/**
 * 标签治理 REST API
 */
class TagGovernanceController extends BaseController
{
    public function registerRoutes(): void
    {
        $ns = $this->namespace;

        // 健康度摘要
        register_rest_route($ns, '/tag-governance/health', [
            'methods'  => 'GET',
            'callback' => [$this, 'getHealth'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 合并建议列表
        register_rest_route($ns, '/tag-governance/suggestions', [
            'methods'  => 'GET',
            'callback' => [$this, 'getSuggestions'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 执行合并
        register_rest_route($ns, '/tag-governance/merge', [
            'methods'  => 'POST',
            'callback' => [$this, 'mergeTags'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 忽略建议
        register_rest_route($ns, '/tag-governance/suggestions/(?P<id>\d+)/ignore', [
            'methods'  => 'POST',
            'callback' => [$this, 'ignoreSuggestion'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 清理碎片标签
        register_rest_route($ns, '/tag-governance/clean-fragments', [
            'methods'  => 'POST',
            'callback' => [$this, 'cleanFragments'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 保护/取消保护
        register_rest_route($ns, '/tag-governance/protect', [
            'methods'  => 'POST',
            'callback' => [$this, 'toggleProtect'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 受保护标签列表
        register_rest_route($ns, '/tag-governance/protected', [
            'methods'  => 'GET',
            'callback' => [$this, 'getProtected'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 手动触发巡检
        register_rest_route($ns, '/tag-governance/scan', [
            'methods'  => 'POST',
            'callback' => [$this, 'runScan'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // AI 一键合并分析
        register_rest_route($ns, '/tag-governance/ai-merge-analysis', [
            'methods'  => 'POST',
            'callback' => [$this, 'aiMergeAnalysis'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 执行AI合并
        register_rest_route($ns, '/tag-governance/ai-merge-execute', [
            'methods'  => 'POST',
            'callback' => [$this, 'aiMergeExecute'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);

        // 同义词表统计
        register_rest_route($ns, '/tag-governance/synonym-stats', [
            'methods'  => 'GET',
            'callback' => [$this, 'synonymStats'],
            'permission_callback' => function () { return current_user_can('manage_options'); },
        ]);
    }

    public function getHealth(): WP_REST_Response
    {
        $gov = new TagGovernance();
        return $this->success($gov->getHealthSummary());
    }

    public function getSuggestions(WP_REST_Request $request): WP_REST_Response
    {
        $gov = new TagGovernance();
        $status = $request->get_param('status') ?: 'pending';
        return $this->success($gov->getMergeSuggestions($status));
    }

    public function mergeTags(WP_REST_Request $request): WP_REST_Response
    {
        $sourceId = (int) $request->get_param('source_id');
        $targetId = (int) $request->get_param('target_id');

        if (!$sourceId || !$targetId) {
            return $this->error('缺少标签ID');
        }

        $gov = new TagGovernance();
        $sourceTerm = get_term($sourceId, 'post_tag');
        $targetTerm = get_term($targetId, 'post_tag');
        $result = $gov->mergeTags($sourceId, $targetId);
        if ($result['success']) {
            $srcName = $sourceTerm && !is_wp_error($sourceTerm) ? $sourceTerm->name : "ID:{$sourceId}";
            $tgtName = $targetTerm && !is_wp_error($targetTerm) ? $targetTerm->name : "ID:{$targetId}";
            Logger::info('tag_governance', "合并标签: {$srcName} → {$tgtName}", ['posts' => $result['count'] ?? 0]);
        }
        return $result['success'] ? $this->success($result) : $this->error($result['message']);
    }

    public function ignoreSuggestion(WP_REST_Request $request): WP_REST_Response
    {
        $id = (int) $request->get_param('id');
        $gov = new TagGovernance();
        $gov->ignoreSuggestion($id);
        return $this->success(['ignored' => true]);
    }

    public function cleanFragments(): WP_REST_Response
    {
        $gov = new TagGovernance();
        $result = $gov->cleanFragments();
        Logger::info('tag_governance', "清理碎片标签: 删除 {$result['cleaned']} 个");
        return $this->success($result);
    }

    public function toggleProtect(WP_REST_Request $request): WP_REST_Response
    {
        $termId = (int) $request->get_param('term_id');
        $protect = (bool) $request->get_param('protect');

        if (!$termId) return $this->error('缺少标签ID');

        $gov = new TagGovernance();
        if ($protect) {
            $gov->protectTag($termId);
        } else {
            $gov->unprotectTag($termId);
        }
        return $this->success(['term_id' => $termId, 'protected' => $protect]);
    }

    public function getProtected(): WP_REST_Response
    {
        $gov = new TagGovernance();
        $ids = $gov->getProtectedIds();
        $tags = [];
        foreach ($ids as $id) {
            $term = get_term($id, 'post_tag');
            if ($term && !is_wp_error($term)) {
                $tags[] = ['term_id' => $id, 'name' => $term->name];
            }
        }
        return $this->success($tags);
    }

    public function runScan(): WP_REST_Response
    {
        $gov = new TagGovernance();
        $result = $gov->runHealthCheck();
        Logger::info('tag_governance', "标签巡检完成: 总数{$result['total']}, 健康{$result['healthy']}, 虚弱{$result['weak']}, 碎片{$result['fragment']}");
        return $this->success($result);
    }

    public function aiMergeAnalysis(WP_REST_Request $request): WP_REST_Response
    {
        $useAI = (bool) $request->get_param('use_ai');
        $gov = new TagGovernance();
        return $this->success($gov->aiMergeAnalysis($useAI));
    }

    public function aiMergeExecute(WP_REST_Request $request): WP_REST_Response
    {
        $merges = $request->get_json_params()['merges'] ?? [];
        if (empty($merges)) return $this->error('请提供合并方案');
        $gov = new TagGovernance();
        $result = $gov->executeAiMerge($merges);
        Logger::info('tag_governance', "AI合并执行: 合并{$result['merged']}组, 替换{$result['replaced_posts']}篇文章, 补标签{$result['tags_filled']}个");
        return $this->success($result);
    }

    public function synonymStats(): WP_REST_Response
    {
        return $this->success(\XZD\AI\V5\SEO\TagGovernance::getSynonymStats());
    }
}
