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

class AISB_Integrations {

    public static function content_assist_active() {
        return class_exists('AICA_Content_Helpers') || function_exists('aica_detect_faq_sections');
    }

    public static function faq_sections_for_post($post_id) {
        if (function_exists('aica_detect_faq_sections')) {
            return aica_detect_faq_sections($post_id);
        }
        return self::detect_faq_sections_fallback($post_id);
    }

    public static function has_faq_content($post_id) {
        return !empty(self::faq_sections_for_post($post_id));
    }

    private static function detect_faq_sections_fallback($post_id) {
        $post = get_post($post_id);
        if (!$post) {
            return [];
        }
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core content filter required to parse blocks/shortcodes in post body.
        $html = apply_filters('the_content', $post->post_content);
        $pairs = [];
        if (preg_match_all('/<h[2-4][^>]*>(.*?)<\/h[2-4]>\s*(<p>.*?<\/p>)/is', $html, $m, PREG_SET_ORDER)) {
            foreach ($m as $match) {
                $q = wp_strip_all_tags($match[1]);
                $a = wp_strip_all_tags($match[2]);
                if (strlen($q) > 5 && strlen($a) > 10) {
                    $pairs[] = ['question' => $q, 'answer' => $a];
                }
            }
        }
        return array_slice($pairs, 0, 20);
    }

    public static function build_faq_schema($post_id) {
        $pairs = self::faq_sections_for_post($post_id);
        if (empty($pairs)) {
            return new WP_Error('aisb_no_faq', __('No FAQ sections detected in content.', 'pewit-ai-schema-builder'));
        }
        $entities = [];
        foreach ($pairs as $pair) {
            $entities[] = [
                '@type'          => 'Question',
                'name'           => $pair['question'],
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text'  => $pair['answer'],
                ],
            ];
        }
        return [
            '@context'   => 'https://schema.org',
            '@type'      => 'FAQPage',
            'mainEntity' => $entities,
        ];
    }
}
