<?php

namespace XZD\AI\V5\SEO;

/**
 * LinkNetwork — 全站内链网络分析
 *
 * 提供反向内链、孤立文章检测、内链建议等数据
 *
 * @since V3.2.0
 */
class LinkNetwork
{
    /**
     * 获取反向内链：哪些文章链接到了指定文章
     */
    public function getBacklinks(int $postId, int $limit = 20): array
    {
        global $wpdb;
        $permalink = get_permalink($postId);
        if (!$permalink) return [];

        $slug = preg_quote(get_post_field('post_name', $postId) ?: '', '/');

        // 搜索其他文章中包含当前文章链接的
        $posts = $wpdb->get_results($wpdb->prepare(
            "SELECT ID, post_title, post_date
             FROM {$wpdb->posts}
             WHERE post_status = 'publish' AND post_type = 'post'
             AND ID != %d
             AND (post_content LIKE %s OR post_content LIKE %s)
             ORDER BY post_date DESC
             LIMIT %d",
            $postId,
            '%' . $wpdb->esc_like($permalink) . '%',
            $slug ? '%/' . $slug . '%' : '%##NOMATCH##%',
            $limit
        ));

        return array_map(function ($p) {
            return ['post_id' => (int) $p->ID, 'title' => $p->post_title, 'date' => $p->post_date];
        }, $posts ?: []);
    }

    /**
     * 检测孤立文章：没有任何内链指向的文章
     */
    public function findOrphans(int $limit = 50): array
    {
        global $wpdb;

        $allPosts = get_posts([
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => $limit,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ]);

        $orphans = [];
        foreach ($allPosts as $post) {
            $backlinks = $this->getBacklinks($post->ID, 1);
            if (empty($backlinks)) {
                // 再检查是否有任何文章的post_content包含该文章slug
                $slug = $post->post_name;
                if ($slug) {
                    $count = (int) $wpdb->get_var($wpdb->prepare(
                        "SELECT COUNT(*) FROM {$wpdb->posts}
                         WHERE post_status = 'publish' AND post_type = 'post'
                         AND ID != %d AND post_content LIKE %s",
                        $post->ID, '%/' . $slug . '%'
                    ));
                    if ($count === 0) {
                        $orphans[] = ['post_id' => $post->ID, 'title' => $post->post_title, 'date' => $post->post_date];
                    }
                }
            }
        }

        return $orphans;
    }

    /**
     * 获取内链建议：为指定文章推荐可能的内链目标
     */
    public function getSuggestions(int $postId, int $limit = 5): array
    {
        $post = get_post($postId);
        if (!$post) return [];

        // 同分类的其他文章
        $cats = wp_get_post_categories($postId);
        $tags = wp_get_post_tags($postId, ['fields' => 'ids']);

        $suggestions = get_posts([
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => $limit,
            'exclude'        => [$postId],
            'category__in'   => $cats,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ]);

        return array_map(function ($p) {
            return ['post_id' => $p->ID, 'title' => $p->post_title, 'url' => get_permalink($p)];
        }, $suggestions);
    }
}
