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

/**
 * E-E-A-T analysis — Experience, Expertise, Authoritativeness, Trust.
 * Returns a sub-score per pillar, detected signals and missing signals,
 * plus prioritized recommendations.
 */
class AIVT_EEAT {

    public static function pillars() {
        return [
            'experience'     => __('Experience', 'pewit-geo-analysis-tool'),
            'expertise'      => __('Expertise', 'pewit-geo-analysis-tool'),
            'authoritativeness' => __('Authoritativeness', 'pewit-geo-analysis-tool'),
            'trust'          => __('Trust', 'pewit-geo-analysis-tool'),
        ];
    }

    /**
     * @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'));
        }
        $signals = self::onpage_signals($post_id, $ctx);
        $prompt = self::build_prompt($ctx, $signals);
        $json = AIVT_API::complete_json($prompt, 1500);
        if (is_wp_error($json)) {
            return $json;
        }

        $pillars = self::pillars();
        $scores = [];
        $sum = 0;
        $raw = isset($json['pillars']) && is_array($json['pillars']) ? $json['pillars'] : [];
        foreach ($pillars as $key => $label) {
            $r = $raw[$key] ?? null;
            $val = is_array($r) ? (int) ($r['score'] ?? 0) : (int) $r;
            $val = AIVT_API::clamp_score($val);
            $scores[$key] = [
                'label' => $label,
                'score' => $val,
                'note'  => sanitize_text_field(is_array($r) ? ($r['note'] ?? '') : ''),
            ];
            $sum += $val;
        }
        $overall = count($scores) ? AIVT_API::clamp_score($sum / count($scores)) : 0;

        $data = [
            'overall'  => $overall,
            'pillars'  => $scores,
            'present'  => array_values(array_filter(array_map('sanitize_text_field', (array) ($json['present'] ?? [])))),
            'missing'  => array_values(array_filter(array_map('sanitize_text_field', (array) ($json['missing'] ?? [])))),
            'recommendations' => array_slice(array_values(array_filter(array_map('sanitize_text_field', (array) ($json['recommendations'] ?? [])))), 0, 8),
            'signals'  => $signals,
        ];
        return AIVT_Store::save($post_id, AIVT_Store::META_EEAT, $data);
    }

    /** Deterministic on-page/author trust signals. */
    public static function onpage_signals($post_id, array $ctx) {
        $post = get_post($post_id);
        $author_id = $post ? (int) $post->post_author : 0;
        $author_bio = $author_id ? get_the_author_meta('description', $author_id) : '';
        return [
            'has_author'       => !empty($ctx['author']),
            'author_bio'       => $author_bio !== '',
            'has_outbound_links' => (bool) preg_match('/<a [^>]*href=["\']https?:\/\//i', (string) ($post->post_content ?? '')),
            'has_date'         => true,
            'site_has_about'   => (bool) get_page_by_path('about'),
            'site_has_contact' => (bool) get_page_by_path('contact'),
        ];
    }

    private static function build_prompt(array $ctx, array $signals) {
        $context = AIVT_API::context_block();
        $p  = "You are a Google E-E-A-T and trust evaluator. Rate this page on Experience, Expertise, Authoritativeness and Trust (each 0-100) as an AI answer engine would judge whether to rely on it.\n";
        $p .= "Give a short note per pillar, a list of trust signals present, a list of missing signals, and 3-6 prioritized recommendations.\n\n";
        $p .= "Return ONLY JSON:\n";
        $p .= '{"pillars":{"experience":{"score":0,"note":""},"expertise":{"score":0,"note":""},"authoritativeness":{"score":0,"note":""},"trust":{"score":0,"note":""}},"present":[""],"missing":[""],"recommendations":[""]}'."\n\n";
        if ($context) {
            $p .= "Site context:\n{$context}\n\n";
        }
        $p .= "Measured signals: " . wp_json_encode($signals) . "\n\n";
        $p .= "PAGE\nTitle: {$ctx['title']}\nAuthor: {$ctx['author']}\nURL: {$ctx['url']}\nContent:\n{$ctx['content']}\n";
        return $p;
    }
}
