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

/**
 * Q&A section generation — a richer, conversational question/answer block aligned
 * with how people actually ask AI assistants. Distinct from FAQ: questions are
 * phrased as natural-language queries (the kind users type into ChatGPT/Perplexity)
 * and answers can be longer and more explanatory.
 */
class AIVT_QA {

    /**
     * @return array|WP_Error  ['items'=>[['query'=>,'answer'=>,'intent'=>], ...]]
     */
    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} natural-language questions real users would ask an AI assistant (ChatGPT, Perplexity, Google AI) that this page can answer, with clear answers.\n";
        $p .= "Phrase questions conversationally (how people actually type), cover different search intents (informational, comparison, how-to, local), and answer in an answer-first style grounded ONLY in the page content.\n";
        $p .= "For each item include the question (query), the answer, and the intent label.\n\n";
        $p .= "Return ONLY JSON: {\"items\":[{\"query\":\"\",\"answer\":\"\",\"intent\":\"\"}]}\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, 1800);
        if (is_wp_error($json)) {
            return $json;
        }
        $items = self::clean_items($json['items'] ?? []);
        if (empty($items)) {
            return new WP_Error('aivt_empty', __('No Q&A items were generated. Try again.', 'pewit-geo-analysis-tool'));
        }
        $data = ['items' => $items];
        AIVT_Store::save($post_id, AIVT_Store::META_QA, $data);
        return $data;
    }

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

    public static function render_blocks($items, $heading = '') {
        $out = '';
        if ($heading !== '') {
            $out .= "<!-- wp:heading -->\n<h2>" . esc_html($heading) . "</h2>\n<!-- /wp:heading -->\n\n";
        }
        foreach ($items as $item) {
            $out .= "<!-- wp:heading {\"level\":3} -->\n<h3>" . esc_html($item['query']) . "</h3>\n<!-- /wp:heading -->\n\n";
            $out .= "<!-- wp:paragraph -->\n<p>" . wp_kses_post($item['answer']) . "</p>\n<!-- /wp:paragraph -->\n\n";
        }
        return trim($out);
    }
}
