<?php

declare(strict_types=1);

namespace SeoScope\Services;

/**
 * Builds LLM payload for Long Tail report SEO AI Assistant.
 */
final class SeoAiLongTailPayloadService
{
    public const SCHEMA_VERSION = 1;

    public const MAX_QUERIES = 25;

    /**
     * @param list<array<string, mixed>> $rows From {@see \SeoScope\Repositories\GscLongTailRepository::listForRange()}
     * @param array{
     *   preset:string,
     *   device:string,
     *   country:string,
     *   range_start:string,
     *   range_end:string,
     *   min_terms:int,
     *   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));
        $normalized = [];
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            $q = trim((string) ($row['query'] ?? ''));
            if ($q === '') {
                continue;
            }
            $normalized[] = [
                'query' => $q,
                'terms' => max(1, (int) ($row['terms'] ?? 0)),
                '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 !== [];

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

        $payload = [
            'schema_version' => self::SCHEMA_VERSION,
            'context' => 'long_tail_report',
            'filters' => [
                'preset' => (string) ($meta['preset'] ?? 'last_28_days'),
                'device' => (string) ($meta['device'] ?? 'all'),
                'country' => (string) ($meta['country'] ?? 'all'),
            ],
            'period' => [
                'start' => (string) ($meta['range_start'] ?? ''),
                'end' => (string) ($meta['range_end'] ?? ''),
            ],
            'thresholds' => [
                'min_terms' => max(1, (int) ($meta['min_terms'] ?? 4)),
            ],
            '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,
                'avg_terms_top' => count($normalized) > 0 ? round($sumTerms / count($normalized), 2) : null,
            ],
            'queries' => $normalized,
            'model_notes' => [
                'long_tail_meaning' => 'Long-tail queries are multi-word searches (word count ≥ min_terms). Rows follow the table sort order.',
                'constraints' => 'Interpret only listed queries and portfolio fields. Do not invent landing URLs (not provided).',
            ],
        ];

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