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

/**
 * Competitor analysis — measures share-of-voice between the brand and configured
 * competitors across a set of AI prompts, then asks the model for a gap analysis
 * (why competitors get recommended, what to improve). Pro/Agency feature.
 */
class AIVT_Competitors {

    /**
     * @return array|WP_Error
     */
    public static function analyze($max_prompts = 5) {
        $competitors = aivt_competitors_list();
        if (empty($competitors)) {
            return new WP_Error('aivt_no_competitors', __('Add at least one competitor in Settings first.', 'pewit-geo-analysis-tool'));
        }
        $brand = aivt_site_brand();

        $prompts = AIVT_Prompt_Test::get_monitored_prompts();
        if (empty($prompts)) {
            $prompts = AIVT_Prompt_Test::suggest_prompts((int) $max_prompts);
            if (is_wp_error($prompts)) {
                return $prompts;
            }
        }
        $prompts = array_slice($prompts, 0, max(1, min(10, (int) $max_prompts)));

        $tally = [$brand => 0];
        foreach ($competitors as $c) {
            $tally[$c] = 0;
        }
        $runs = [];
        foreach ($prompts as $prompt) {
            $res = AIVT_Prompt_Test::run($prompt);
            if (is_wp_error($res)) {
                continue;
            }
            $answer_l = function_exists('mb_strtolower') ? mb_strtolower($res['answer']) : strtolower($res['answer']);
            if (!empty($res['mentioned'])) {
                $tally[$brand]++;
            }
            $row_comps = [];
            foreach ($competitors as $c) {
                $needle = function_exists('mb_strtolower') ? mb_strtolower($c) : strtolower($c);
                if ($needle !== '' && aivt_mb_strpos($answer_l, $needle) !== false) {
                    $tally[$c]++;
                    $row_comps[] = $c;
                }
            }
            $runs[] = [
                'prompt'      => $res['prompt'],
                'brand'       => !empty($res['mentioned']),
                'competitors' => $row_comps,
            ];
        }

        $total_runs = max(1, count($runs));
        $share = [];
        foreach ($tally as $name => $count) {
            $share[$name] = (int) round(($count / $total_runs) * 100);
        }
        arsort($share);

        $gap = self::gap_analysis($brand, $competitors, $runs);
        $report = [
            'brand'       => $brand,
            'competitors' => $competitors,
            'runs'        => $runs,
            'share'       => $share,
            'total_runs'  => $total_runs,
            'gap'         => is_wp_error($gap) ? [] : $gap,
        ];
        return AIVT_Store::save_competitor_report($report);
    }

    private static function gap_analysis($brand, $competitors, $runs) {
        $context = AIVT_API::context_block();
        $summary = [];
        foreach ($runs as $r) {
            $summary[] = ($r['brand'] ? '[brand✓] ' : '[brand✗] ') . $r['prompt'] . ' → ' . (empty($r['competitors']) ? 'none' : implode(', ', $r['competitors']));
        }
        $p  = "You are an AI-visibility strategist. The brand \"{$brand}\" competes with: " . implode(', ', $competitors) . ".\n";
        $p .= "Below are AI-prompt results showing whether the brand and competitors appeared.\n\n" . implode("\n", $summary) . "\n\n";
        if ($context) {
            $p .= "Brand context:\n{$context}\n\n";
        }
        $p .= "Explain in JSON: why competitors get surfaced (factors), the brand's biggest visibility gaps, and 4-7 concrete actions to get the brand recommended more often by AI assistants.\n";
        $p .= "Return ONLY JSON: {\"factors\":[\"\"],\"gaps\":[\"\"],\"actions\":[\"\"]}\n";

        $json = AIVT_API::complete_json($p, 1200);
        if (is_wp_error($json)) {
            return $json;
        }
        return [
            'factors' => array_slice(array_values(array_filter(array_map('sanitize_text_field', (array) ($json['factors'] ?? [])))), 0, 8),
            'gaps'    => array_slice(array_values(array_filter(array_map('sanitize_text_field', (array) ($json['gaps'] ?? [])))), 0, 8),
            'actions' => array_slice(array_values(array_filter(array_map('sanitize_text_field', (array) ($json['actions'] ?? [])))), 0, 10),
        ];
    }
}
