<?php

declare(strict_types=1);

namespace SeoScope\Services;

/**
 * Builds LLM payload for Question Queries report SEO AI Assistant.
 */
final class SeoAiQuestionQueriesPayloadService
{
    public const SCHEMA_VERSION = 1;

    public const MAX_QUERIES = 25;

    /** @var int Max question terms listed in payload for the model */
    private const MAX_TERMS_IN_PAYLOAD = 20;

    /**
     * @param list<array<string, mixed>> $rows From {@see \SeoScope\Repositories\GscQuestionQueriesRepository::listForRange()}
     * @param array{
     *   preset:string,
     *   device:string,
     *   country:string,
     *   range_start:string,
     *   range_end:string,
     *   question_terms:list<string>,
     *   sort:string,
     *   dir:string,
     *   total_queries:int,
     * } $meta
     *
     * @return array{ready:bool, payload:array<string,mixed>}
     */
    public function build(array $rows, array $meta): array
    {
        $total = max(0, (int) ($meta['total_queries'] ?? 0));
        $terms = is_array($meta['question_terms'] ?? null) ? $meta['question_terms'] : [];
        $terms = array_values(array_filter(array_map(static fn ($t) => trim((string) $t), $terms), static fn ($t) => $t !== ''));

        $normalized = [];
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            $q = trim((string) ($row['query'] ?? ''));
            if ($q === '') {
                continue;
            }
            $normalized[] = [
                'query' => $q,
                'clicks' => max(0, (int) ($row['clicks'] ?? 0)),
                'impressions' => max(0, (int) ($row['impressions'] ?? 0)),
                'ctr' => round((float) ($row['ctr'] ?? 0), 6),
                'position' => round((float) ($row['position'] ?? 0), 4),
            ];
            if (count($normalized) >= self::MAX_QUERIES) {
                break;
            }
        }

        $ready = $total > 0 && $normalized !== [] && $terms !== [];

        $sumImpr = 0;
        $sumClicks = 0;
        $sumPosWeighted = 0.0;
        foreach ($normalized as $k) {
            $sumImpr += (int) $k['impressions'];
            $sumClicks += (int) $k['clicks'];
            $sumPosWeighted += (float) $k['position'] * (int) $k['impressions'];
        }

        $termsForModel = array_slice($terms, 0, self::MAX_TERMS_IN_PAYLOAD);

        $payload = [
            'schema_version' => self::SCHEMA_VERSION,
            'context' => 'question_queries_report',
            'filters' => [
                'preset' => (string) ($meta['preset'] ?? 'last_28_days'),
                'device' => (string) ($meta['device'] ?? 'all'),
                'country' => (string) ($meta['country'] ?? 'all'),
                'question_terms' => $termsForModel,
                'question_terms_count' => count($terms),
            ],
            'period' => [
                'start' => (string) ($meta['range_start'] ?? ''),
                'end' => (string) ($meta['range_end'] ?? ''),
            ],
            'sort' => [
                'column' => (string) ($meta['sort'] ?? 'clicks'),
                'direction' => strtoupper((string) ($meta['dir'] ?? 'DESC')) === 'ASC' ? 'ASC' : 'DESC',
            ],
            'portfolio' => [
                'total_queries' => $total,
                'rows_sent_to_model' => count($normalized),
                'sum_impressions_top' => $sumImpr,
                'sum_clicks_top' => $sumClicks,
                'weighted_avg_position_top' => $sumImpr > 0 ? round($sumPosWeighted / $sumImpr, 4) : null,
            ],
            'queries' => $normalized,
            'model_notes' => [
                'question_queries_meaning' => 'Rows are search queries whose text matches at least one configured question term (substring match, case-insensitive).',
                'constraints' => 'Interpret only listed queries, question terms, and portfolio fields. Do not invent landing URLs (not provided).',
            ],
        ];

        return ['ready' => $ready, 'payload' => $payload];
    }
}
