<?php
if (!defined('ABSPATH')) exit;

/**
 * AI citability analysis — how likely an AI assistant is to quote/cite passages from
 * this page. Surfaces the most quotable statements, flags weak spots (vague claims,
 * unsourced stats, missing definitions) and suggests citable rewrites.
 */
class AIVT_Citability {

    /**
     * @return array|WP_Error
     */
    public static function analyze($post_id) {
        $ctx = AIVT_API::post_context($post_id, 6000);
        if (empty($ctx)) {
            return new WP_Error('aivt_no_post', __('Post not found', 'pewit-geo-analysis-tool'));
        }
        $context = AIVT_API::context_block();

        $p  = "Assess how citable this page is for AI answer engines that quote sources.\n";
        $p .= "Return: an overall citability score 0-100; the 3-6 most quotable statements already in the text (verbatim, short); issues that reduce citability (vague claims, unsourced statistics, no clear definitions, buried answers); and 3-6 concrete 'add a citable sentence like this' suggestions written in answer-first style and grounded in the content.\n\n";
        $p .= "Return ONLY JSON:\n";
        $p .= '{"score":0,"summary":"","quotable":[""],"issues":[""],"suggestions":[""]}'."\n\n";
        if ($context) {
            $p .= "Site context:\n{$context}\n\n";
        }
        $p .= "PAGE\nTitle: {$ctx['title']}\nURL: {$ctx['url']}\nContent:\n{$ctx['content']}\n";

        $json = AIVT_API::complete_json($p, 1600);
        if (is_wp_error($json)) {
            return $json;
        }
        $data = [
            'score'       => AIVT_API::clamp_score($json['score'] ?? 0),
            'summary'     => sanitize_text_field((string) ($json['summary'] ?? '')),
            'quotable'    => array_slice(array_values(array_filter(array_map('sanitize_text_field', (array) ($json['quotable'] ?? [])))), 0, 8),
            'issues'      => array_slice(array_values(array_filter(array_map('sanitize_text_field', (array) ($json['issues'] ?? [])))), 0, 8),
            'suggestions' => array_slice(array_values(array_filter(array_map('sanitize_text_field', (array) ($json['suggestions'] ?? [])))), 0, 8),
        ];
        return AIVT_Store::save($post_id, AIVT_Store::META_CITE, $data);
    }
}
