<?php

if (!defined('ABSPATH')) {
    exit;
}

/** Builds a bounded read-only snapshot of published first-party WordPress content. */
final class Aysa_AI_Visibility_Knowledge_Snapshot {
    const MAX_ITEMS = 100;
    const MAX_ITEM_CHARS = 12000;
    const MAX_PAYLOAD_BYTES = 1800000;

    public static function build() {
        $home = esc_url_raw((string) home_url('/'));
        if (strtolower((string) wp_parse_url($home, PHP_URL_SCHEME)) !== 'https') {
            return new WP_Error(
                'ai_visibility_knowledge_https_required',
                __('Knowledge Base snapshots require an HTTPS site URL.', 'aysaaiseo')
            );
        }
        $posts = get_posts(array(
            'post_type' => array('page', 'post'),
            'post_status' => 'publish',
            'posts_per_page' => self::MAX_ITEMS,
            'orderby' => 'modified',
            'order' => 'DESC',
            'no_found_rows' => true,
            'suppress_filters' => false,
        ));
        $items = array();
        $bytes = 0;
        foreach (is_array($posts) ? $posts : array() as $post) {
            if (!($post instanceof WP_Post)) {
                continue;
            }
            $text = trim(wp_strip_all_tags(strip_shortcodes((string) $post->post_content), true));
            $text = mb_substr($text, 0, self::MAX_ITEM_CHARS);
            $item = array(
                'id' => absint($post->ID),
                'type' => sanitize_key((string) $post->post_type),
                'title' => sanitize_text_field((string) get_the_title($post)),
                'canonical_url' => esc_url_raw((string) get_permalink($post)),
                'modified_gmt' => sanitize_text_field((string) $post->post_modified_gmt),
                'text' => $text,
            );
            $encoded = wp_json_encode($item, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            if (!is_string($encoded) || $bytes + strlen($encoded) > self::MAX_PAYLOAD_BYTES) {
                break;
            }
            $items[] = $item;
            $bytes += strlen($encoded);
        }
        if (!$items) {
            return new WP_Error(
                'ai_visibility_knowledge_snapshot_empty',
                __('No published pages or posts are available for the Knowledge Base snapshot.', 'aysaaiseo')
            );
        }
        $content = wp_json_encode(array(
            'schema_version' => 'aysa_wordpress_knowledge_snapshot_v1',
            'site_url' => $home,
            'site_name' => sanitize_text_field((string) get_bloginfo('name')),
            'language' => sanitize_text_field((string) get_bloginfo('language')),
            'items' => $items,
        ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        if (!is_string($content)) {
            return new WP_Error('ai_visibility_knowledge_snapshot_encode_failed', __('The site snapshot could not be encoded.', 'aysaaiseo'));
        }
        return array(
            'external_key' => 'wordpress:published-content',
            'source_type' => 'wordpress_snapshot',
            // translators: %d is the number of published WordPress items in the snapshot.
            'title' => sprintf(__('Published WordPress content (%d items)', 'aysaaiseo'), count($items)),
            'canonical_url' => $home,
            'content' => $content,
            'mime_type' => 'application/json',
            'size_bytes' => strlen($content),
            'official_source' => true,
            'confirmed_by_user' => false,
            'sensitivity' => 'normal',
            'owner_name' => sanitize_text_field((string) get_bloginfo('name')),
            'last_fetched_at' => gmdate('c'),
            // translators: %d is the number of published WordPress items in the snapshot.
            'evidence_excerpt' => sprintf(__('Read-only snapshot of %d currently published WordPress items.', 'aysaaiseo'), count($items)),
        );
    }
}
