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

/**
 * FAQ generation — produces question/answer pairs optimized for AI answer engines
 * and FAQPage schema. Manual generation is free (BYOK); bulk/auto runs via the queue (Pro).
 */
class AIVT_FAQ {

    /**
     * @return array|WP_Error  ['pairs'=>[['question'=>,'answer'=>], ...]]
     */
    public static function generate($post_id, $count = 5) {
        $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'));
        }
        $count = max(2, min(12, (int) $count));
        $context = AIVT_API::context_block();

        $p  = "Generate {$count} frequently asked questions with concise, direct, factual answers for the page below.\n";
        $p .= "Write answers an AI assistant could quote verbatim: lead with the answer in the first sentence, 2-4 sentences max, no fluff, no marketing.\n";
        $p .= "Base every answer ONLY on the page content. Do not invent facts, prices or claims.\n\n";
        $p .= "Return ONLY JSON: {\"pairs\":[{\"question\":\"\",\"answer\":\"\"}]}\n\n";
        if ($context) {
            $p .= "Site context:\n{$context}\n\n";
        }
        if (!empty($ctx['focus_keyword'])) {
            $p .= "Target keyword (favor this intent): {$ctx['focus_keyword']}\n";
        }
        $p .= "PAGE\nTitle: {$ctx['title']}\nContent:\n{$ctx['content']}\n";

        $json = AIVT_API::complete_json($p, 1600);
        if (is_wp_error($json)) {
            return $json;
        }
        $pairs = self::clean_pairs($json['pairs'] ?? ($json[0] ?? []));
        if (empty($pairs)) {
            return new WP_Error('aivt_empty', __('No FAQ pairs were generated. Try again.', 'pewit-geo-analysis-tool'));
        }
        $data = ['pairs' => $pairs];
        AIVT_Store::save($post_id, AIVT_Store::META_FAQ, $data);
        return $data;
    }

    public static function clean_pairs($raw) {
        if (!is_array($raw)) {
            return [];
        }
        $pairs = [];
        foreach ($raw as $row) {
            if (!is_array($row)) {
                continue;
            }
            $q = trim((string) ($row['question'] ?? $row['q'] ?? ''));
            $a = trim((string) ($row['answer'] ?? $row['a'] ?? ''));
            if ($q !== '' && $a !== '') {
                $pairs[] = [
                    'question' => sanitize_text_field($q),
                    'answer'   => wp_kses_post($a),
                ];
            }
        }
        return $pairs;
    }

    /** FAQPage JSON-LD from saved/passed pairs. */
    public static function build_schema($post_id, $pairs = null) {
        if ($pairs === null) {
            $saved = AIVT_Store::get($post_id, AIVT_Store::META_FAQ);
            $pairs = $saved['pairs'] ?? [];
        }
        if (empty($pairs)) {
            return null;
        }
        $entities = [];
        foreach ($pairs as $pair) {
            $entities[] = [
                '@type'          => 'Question',
                'name'           => $pair['question'],
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text'  => wp_strip_all_tags($pair['answer']),
                ],
            ];
        }
        return [
            '@context'   => 'https://schema.org',
            '@type'      => 'FAQPage',
            'mainEntity' => $entities,
        ];
    }

    /** Render Gutenberg blocks for the pairs (for inserting into the post). */
    public static function render_blocks($pairs, $heading = '') {
        $out = '';
        if ($heading !== '') {
            $out .= "<!-- wp:heading -->\n<h2>" . esc_html($heading) . "</h2>\n<!-- /wp:heading -->\n\n";
        }
        foreach ($pairs as $pair) {
            $out .= "<!-- wp:heading {\"level\":3} -->\n<h3>" . esc_html($pair['question']) . "</h3>\n<!-- /wp:heading -->\n\n";
            $out .= "<!-- wp:paragraph -->\n<p>" . wp_kses_post($pair['answer']) . "</p>\n<!-- /wp:paragraph -->\n\n";
        }
        return trim($out);
    }
}
