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

/**
 * Entity detection — extracts the named entities (people, organizations, places,
 * products, concepts) an AI engine would associate with the page, flags which are
 * ambiguous, and suggests knowledge-graph links (sameAs) and topical authority
 * (knowsAbout) to strengthen entity clarity.
 */
class AIVT_Entities {

    /**
     * @return array|WP_Error  ['entities'=>[...], 'primary'=>string, 'missing'=>[...]]
     */
    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'));
        }
        $prompt = self::build_prompt($ctx);
        $json = AIVT_API::complete_json($prompt, 1400);
        if (is_wp_error($json)) {
            return $json;
        }

        $entities = [];
        $raw = isset($json['entities']) && is_array($json['entities']) ? $json['entities'] : [];
        foreach ($raw as $e) {
            if (!is_array($e) || empty($e['name'])) {
                continue;
            }
            $entities[] = [
                'name'       => sanitize_text_field($e['name']),
                'type'       => sanitize_text_field($e['type'] ?? 'Thing'),
                'role'       => sanitize_text_field($e['role'] ?? ''),
                'salience'   => AIVT_API::clamp_score($e['salience'] ?? 0),
                'ambiguous'  => !empty($e['ambiguous']),
                'sameAs'     => esc_url_raw($e['sameAs'] ?? ''),
            ];
        }
        usort($entities, function ($a, $b) {
            return $b['salience'] <=> $a['salience'];
        });

        $data = [
            'entities'   => array_slice($entities, 0, 30),
            'primary'    => sanitize_text_field((string) ($json['primary'] ?? '')),
            'knows_about'=> array_values(array_filter(array_map('sanitize_text_field', (array) ($json['knowsAbout'] ?? [])))),
            'summary'    => sanitize_text_field((string) ($json['summary'] ?? '')),
        ];
        return AIVT_Store::save($post_id, AIVT_Store::META_ENTITIES, $data);
    }

    private static function build_prompt(array $ctx) {
        $context = AIVT_API::context_block();
        $p  = "Extract the named entities an AI answer engine would associate with this page.\n";
        $p .= "For each entity give: name, type (Person/Organization/Place/Product/Brand/Concept/Event), role on the page, salience 0-100, whether the name is ambiguous (could be confused with something else), and a best-guess authoritative sameAs URL (Wikipedia/Wikidata/official site) or empty string.\n";
        $p .= "Also identify the single primary entity, a knowsAbout list (3-8 topics this page demonstrates authority on), and a one-sentence summary of entity clarity.\n\n";
        $p .= "Return ONLY JSON:\n";
        $p .= '{"primary":"","entities":[{"name":"","type":"","role":"","salience":0,"ambiguous":false,"sameAs":""}],"knowsAbout":[""],"summary":""}'."\n\n";
        if ($context) {
            $p .= "Site context:\n{$context}\n\n";
        }
        $p .= "PAGE\nTitle: {$ctx['title']}\nURL: {$ctx['url']}\nContent:\n{$ctx['content']}\n";
        return $p;
    }
}
