"""Tool esplorativo: ranking delle 9 keyword per volume di ricerca relativo.

SerpApi Compare limit = 5 keyword/call. Per rankare 9, faccio 2 call con Dementia
come ANCHOR comune in entrambe → normalizzo i risultati su Dementia.

Output: lista ordinata desc per "average score normalizzato".
Costa 2 chiamate SerpApi.

Run:
    cd ~/agents && uv run python -m projects.symetrics_trends.betterbrain.rank_keywords
"""

from __future__ import annotations

from statistics import mean
from typing import Any

import yaml
from pathlib import Path

from projects.symetrics_trends.lib import serpapi_trends


HERE = Path(__file__).resolve().parent
CONFIG_PATH = HERE / "config.yaml"


def main():
    with open(CONFIG_PATH) as f:
        cfg = yaml.safe_load(f)
    keywords = cfg["keywords"]
    geo = cfg["geo"]
    timeframe = "today 3-m"

    print(f"Ranking {len(keywords)} keyword US su ultimi 3 mesi...")
    print(f"Keywords: {keywords}\n")

    anchor = "Dementia"
    if anchor not in keywords:
        print(f"ERROR: anchor '{anchor}' deve essere in keywords")
        return

    # Split: anchor + 4 others, anchor + remaining
    others = [k for k in keywords if k != anchor]
    batch1 = [anchor] + others[:4]
    batch2 = [anchor] + others[4:]

    print(f"Batch 1 (compare): {batch1}")
    print(f"Batch 2 (compare): {batch2}\n")

    def fetch_and_avg(batch):
        result = serpapi_trends.fetch_compare(batch, geo, timeframe)
        rows = result.get("rows", [])
        if not rows:
            return {kw: 0.0 for kw in batch}
        avg = {}
        for kw in batch:
            values = [r.get(kw, 0) for r in rows]
            avg[kw] = mean(values) if values else 0.0
        return avg

    print("Fetching batch 1...")
    avg1 = fetch_and_avg(batch1)
    print("Fetching batch 2...")
    avg2 = fetch_and_avg(batch2)

    # Normalize batch2 against batch1 using anchor's average
    if avg1[anchor] > 0 and avg2[anchor] > 0:
        scale = avg1[anchor] / avg2[anchor]
    else:
        scale = 1.0

    combined = {}
    for kw, v in avg1.items():
        combined[kw] = v
    for kw, v in avg2.items():
        if kw != anchor:
            combined[kw] = v * scale

    ranked = sorted(combined.items(), key=lambda x: x[1], reverse=True)

    print(f"\n=== RANKING (avg score normalizzato su {anchor}={avg1[anchor]:.1f}) ===")
    for i, (kw, score) in enumerate(ranked, 1):
        marker = "🥇" if i == 1 else ("🥈" if i == 2 else ("🥉" if i == 3 else "  "))
        marker_in_top5 = " ← TOP 5" if i <= 5 else ""
        print(f"  {marker} #{i:>2}  {kw:30s}  score: {score:6.1f}{marker_in_top5}")

    top5 = [kw for kw, _ in ranked[:5]]
    print(f"\n=== SUGGESTED compare_set ===")
    print("compare_set:")
    for kw in top5:
        print(f'  - "{kw}"')


if __name__ == "__main__":
    main()
