<?php

namespace XZD\AI\V5\Tools;

use XZD\AI\V5\AI\Client;
use XZD\AI\V5\AI\Types;

class SEOManager
{
    /** SEO 综合评分 */
    public static function scoreSEO(array $params, int $userId): ToolResult
    {
        $postId = (int) ($params['post_id'] ?? 0);
        $post = get_post($postId);
        if (!$post) return ToolResult::error('文章不存在');

        $content = mb_substr(wp_strip_all_tags(strip_shortcodes($post->post_content)), 0, 3000);
        $seo = [
            'title' => $post->post_title,
            'title_length' => mb_strlen($post->post_title),
            'slug' => $post->post_name,
            'has_h1' => preg_match('/<h1/i', $post->post_content) === 1,
            'has_h2' => preg_match_all('/<h2/i', $post->post_content),
            'word_count' => mb_strlen(wp_strip_all_tags($post->post_content)),
            'has_images' => preg_match_all('/<img/i', $post->post_content),
            'has_links' => preg_match_all('/<a\s/i', $post->post_content),
            'meta_title' => get_post_meta($postId, '_xzd_ai_seo_title', true) ?: '',
            'meta_description' => get_post_meta($postId, '_xzd_ai_seo_description', true) ?: '',
        ];

        $score = 50
            + ($seo['title_length'] >= 15 && $seo['title_length'] <= 70 ? 10 : 0)
            + ($seo['meta_title'] ? 10 : 0) + ($seo['meta_description'] ? 10 : 0)
            + ($seo['word_count'] > 500 ? 10 : 0) + ($seo['has_images'] > 0 ? 5 : 0)
            + ($seo['has_links'] > 0 ? 5 : 0);

        return ToolResult::success(array_merge($seo, ['score' => min($score, 100)]), "SEO 评分: {$score}/100");
    }

    /** 生成 Schema.org 结构化数据 */
    public static function generateSchema(array $params, int $userId): ToolResult
    {
        $postId = (int) ($params['post_id'] ?? 0);
        $type = $params['schema_type'] ?? 'Article';
        $post = get_post($postId);
        if (!$post) return ToolResult::error('文章不存在');

        $schema = [
            '@context' => 'https://schema.org',
            '@type' => $type,
            'headline' => $post->post_title,
            'datePublished' => $post->post_date,
            'dateModified' => $post->post_modified,
            'author' => ['@type' => 'Person', 'name' => get_the_author_meta('display_name', $post->post_author)],
            'url' => get_permalink($post),
        ];

        if ($type === 'Article' && has_post_thumbnail($postId)) {
            $schema['image'] = get_the_post_thumbnail_url($postId, 'full');
        }

        update_post_meta($postId, '_xzd_ai_schema', wp_json_encode($schema, JSON_UNESCAPED_UNICODE));

        return ToolResult::success(['schema' => $schema], 'Schema 已生成');
    }

    /** 搜索推送 — 只推送已配置密钥的搜索引擎 */
    public static function pushSearch(array $params, int $userId): ToolResult
    {
        $postId = (int) ($params['post_id'] ?? 0);
        $post = get_post($postId);
        if (!$post || $post->post_status !== 'publish') return ToolResult::error('仅已发布文章可推送');

        $permalink = get_permalink($post);
        $results = [];
        $pushed = 0;

        // 百度
        $baiduToken = trim($params['baidu_token'] ?? '');
        if ($baiduToken !== '') {
            $url = 'https://data.zz.baidu.com/urls?site=' . urlencode(home_url()) . '&token=' . urlencode($baiduToken);
            $resp = wp_remote_post($url, ['body' => $permalink, 'timeout' => 10, 'headers' => ['Content-Type' => 'text/plain']]);
            $results['baidu'] = is_wp_error($resp) ? '失败' : '已提交';
            if ($results['baidu'] !== '失败') $pushed++;
        }

        // Bing
        $bingKey = trim($params['bing_key'] ?? '');
        if ($bingKey !== '') {
            $url = 'https://www.bing.com/indexnow?url=' . urlencode($permalink) . '&key=' . urlencode($bingKey);
            $resp = wp_remote_get($url, ['timeout' => 10]);
            $results['bing'] = is_wp_error($resp) ? '失败' : '已提交';
            if ($results['bing'] !== '失败') $pushed++;
        }

        // Google
        $googleKey = trim($params['google_key'] ?? '');
        if ($googleKey !== '') {
            $sitemapUrl = home_url('/sitemap.xml');
            $url = 'https://www.google.com/webmasters/sitemaps/ping?sitemap=' . urlencode($sitemapUrl);
            $resp = wp_remote_get($url, ['timeout' => 10]);
            $results['google'] = is_wp_error($resp) ? '失败' : '已提交';
            if ($results['google'] !== '失败') $pushed++;
        }

        if (empty($results)) {
            return ToolResult::success([], '无搜索引擎已配置密钥，已跳过推送');
        }

        update_post_meta($postId, '_xzd_ai_last_push', current_time('mysql'));
        return ToolResult::success($results, "已推送到 {$pushed} 个搜索引擎");
    }

    /** 死链扫描 */
    public static function scanDeadLink(array $params, int $userId): ToolResult
    {
        $scanCount = (int) ($params['scan_count'] ?? 100);

        // 扫描文章内链
        $posts = get_posts(['post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => $scanCount]);
        $deadLinks = [];

        foreach ($posts as $post) {
            preg_match_all('/href=["\'](https?:\/\/[^"\']+)["\']/i', $post->post_content, $matches);
            foreach (array_slice($matches[1], 0, 20) as $url) {
                $resp = wp_remote_head($url, ['timeout' => 5]);
                $code = is_wp_error($resp) ? 0 : wp_remote_retrieve_response_code($resp);
                if ($code >= 400 || $code === 0) {
                    $deadLinks[] = ['post_id' => $post->ID, 'url' => $url, 'code' => $code];
                }
            }
        }

        return ToolResult::success(['dead_links' => $deadLinks, 'count' => count($deadLinks), 'scanned' => count($posts)]);
    }

    /** 执行流水线 */
    public static function runPipeline(array $params, int $userId): ToolResult
    {
        $postId = (int) ($params['post_id'] ?? 0);
        $stages = $params['stages'] ?? ['generate_tags', 'generate_seo', 'generate_summary'];
        $registry = ToolRegistry::instance();
        $results = [];

        foreach ($stages as $stageId) {
            $tool = $registry->get($stageId);
            if (!$tool) { $results[$stageId] = '工具不存在'; continue; }
            $result = $registry->execute($stageId, ['post_id' => $postId], $userId);
            $results[$stageId] = $result->success ? 'ok' : $result->message;
        }

        return ToolResult::success(['results' => $results], '流水线完成');
    }
}
