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

/**
 * High-level AI orchestration shared by every analysis module.
 * Builds prompts/context, calls the shared LLM client, parses JSON.
 */
class AIVT_API {

    public static function test($api_key = '') {
        $args = aivt_llm_args();
        if ($api_key !== '') {
            $args['api_key'] = $api_key;
        }
        if (empty($args['api_key'])) {
            return ['ok' => false, 'message' => __('API key is empty', 'pewit-geo-analysis-tool')];
        }
        return aivt_llm_localize_test_result(AIVT_LLM_API::test($args));
    }

    /**
     * Gather a normalized context block for a post used across analyses.
     *
     * @return array{title:string,url:string,content:string,excerpt:string,author:string,site:string,brand:string}
     */
    public static function post_context($post_id, $max_chars = 6000) {
        $post = get_post($post_id);
        if (!$post) {
            return [];
        }
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Intentionally applying WordPress core 'the_content' filter to get rendered content.
        $content = wp_strip_all_tags(apply_filters('the_content', $post->post_content));
        $content = trim(preg_replace('/\s+/', ' ', $content));
        if (function_exists('mb_substr')) {
            $content = mb_substr($content, 0, $max_chars);
        } else {
            $content = substr($content, 0, $max_chars);
        }
        $excerpt = has_excerpt($post) ? wp_strip_all_tags(get_the_excerpt($post)) : substr($content, 0, 400);

        return [
            'title'         => get_the_title($post),
            'url'           => get_permalink($post),
            'content'       => $content,
            'excerpt'       => $excerpt,
            'author'        => get_the_author_meta('display_name', $post->post_author),
            'site'          => get_bloginfo('name'),
            'brand'         => aivt_site_brand(),
            'focus_keyword' => class_exists('AIVT_SEO_Bridge') ? AIVT_SEO_Bridge::focus_keyword($post_id) : '',
        ];
    }

    /** Site-wide context line appended to prompts (industry, location, brand). */
    public static function context_block() {
        $s = aivt_get_settings();
        $lines = [];
        $brand = aivt_site_brand();
        if ($brand) {
            $lines[] = 'Brand / business name: ' . $brand;
        }
        if (!empty($s['business_type'])) {
            $lines[] = 'Business type: ' . $s['business_type'];
        }
        if (!empty($s['location'])) {
            $lines[] = 'Primary location / market: ' . $s['location'];
        }
        if (!empty($s['target_keywords'])) {
            $lines[] = 'Target topics / keywords: ' . $s['target_keywords'];
        }
        if (!empty($s['global_context'])) {
            $lines[] = 'Extra context: ' . trim($s['global_context']);
        }
        return $lines ? implode("\n", $lines) : '';
    }

    /**
     * Run a prompt and parse a single JSON object/array from the reply.
     *
     * @return array|WP_Error
     */
    public static function complete_json($prompt, $max_tokens = 1400) {
        $args = aivt_llm_args(['max_tokens' => $max_tokens]);
        if (empty($args['api_key'])) {
            return new WP_Error('aivt_no_key', __('API key is empty', 'pewit-geo-analysis-tool'));
        }
        $text = AIVT_LLM_API::complete($prompt, $args);
        if (is_wp_error($text)) {
            return aivt_llm_localize_error($text);
        }
        $json = self::extract_json($text);
        if ($json === null) {
            return new WP_Error('aivt_bad_json', __('AI response was not valid JSON.', 'pewit-geo-analysis-tool') . ' ' . substr($text, 0, 200));
        }
        return $json;
    }

    /**
     * Run a prompt and return plain text.
     *
     * @return string|WP_Error
     */
    public static function complete_text($prompt, $max_tokens = 1200) {
        $args = aivt_llm_args(['max_tokens' => $max_tokens]);
        if (empty($args['api_key'])) {
            return new WP_Error('aivt_no_key', __('API key is empty', 'pewit-geo-analysis-tool'));
        }
        $text = AIVT_LLM_API::complete($prompt, $args);
        if (is_wp_error($text)) {
            return aivt_llm_localize_error($text);
        }
        return trim((string) $text);
    }

    public static function extract_json($text) {
        $text = trim((string) $text);
        $text = preg_replace('/^```(?:json)?\s*/i', '', $text);
        $text = preg_replace('/```$/', '', $text);
        $data = json_decode($text, true);
        if (is_array($data)) {
            return $data;
        }
        if (preg_match('/[\{\[].*[\}\]]/s', $text, $m)) {
            $data = json_decode($m[0], true);
            if (is_array($data)) {
                return $data;
            }
        }
        return null;
    }

    /** Clamp an integer score into 0–100. */
    public static function clamp_score($value) {
        return max(0, min(100, (int) round((float) $value)));
    }
}
