"""Google Trends kolektorius (pytrends).

- daily: trending_searches (paros top užklausos)
- realtime: realtime_trending_searches (gali būti ribotai pasiekiama)

pytrends palaiko ne visas šalis – jei `pytrends_geo` šaliai nėra,
gražinam tuščią sąrašą.
"""

from __future__ import annotations

import time
from typing import List

from .base import BaseCollector, TrendItem


class GoogleTrendsCollector(BaseCollector):
    name = "google_trends"
    source_type = "google_trends"

    def __init__(self, *, db, http, cfg):
        super().__init__(db=db, http=http, cfg=cfg)
        # importuojam lazily – kad būtų galima paleisti modulius be pytrends
        from pytrends.request import TrendReq  # type: ignore
        self._TrendReq = TrendReq
        self._client = None

    def _client_for(self, hl: str = "en-US", tz: int = 0):
        # Sukuriam naują klientą – pytrends turi vidinį dėmesį tarp gabalų
        return self._TrendReq(hl=hl, tz=tz, timeout=(10, 25), retries=2, backoff_factor=1.5)

    # ----------------------------------------------------------------------
    def collect_for_country(self, country) -> List[TrendItem]:
        items: List[TrendItem] = []
        pn = country.pytrends_geo
        if not pn:
            self.log.debug("Google Trends nepalaiko %s", country.iso_code)
            return items

        hl = (country.primary_language or "en") + ("-" + country.iso_code if country.primary_language else "")
        if not hl or hl == "en":
            hl = "en-US"

        client = self._client_for(hl=hl)

        # ------- Daily trending searches -----------------------------------
        try:
            df = client.trending_searches(pn=pn)
            for rank, row in enumerate(df.itertuples(index=False), start=1):
                kw = str(row[0]).strip()
                if kw:
                    items.append(TrendItem(
                        keyword=kw,
                        trend_type="daily",
                        rank=rank,
                        score=max(0.0, 1.0 - (rank - 1) / max(20, len(df))),
                        language=country.primary_language,
                    ))
            self.log.info("[%s] Google daily: %d trendų", country.iso_code, len(df))
        except Exception as exc:
            self.log.warning("[%s] Google daily klaida: %s", country.iso_code, exc)

        time.sleep(2.0)   # būti mandagiems Google

        # ------- Realtime trending (gali ne visada veikti) ------------------
        try:
            df_rt = client.realtime_trending_searches(pn=country.iso_code)
            for rank, row in enumerate(df_rt.itertuples(index=False), start=1):
                try:
                    title = str(getattr(row, "title", "")).strip()
                    entities = getattr(row, "entityNames", None)
                    if not title:
                        continue
                    items.append(TrendItem(
                        keyword=title,
                        trend_type="realtime",
                        rank=rank,
                        score=max(0.0, 1.0 - (rank - 1) / max(20, len(df_rt))),
                        language=country.primary_language,
                        description=(", ".join(entities) if isinstance(entities, list) else None),
                    ))
                except Exception:
                    continue
            self.log.info("[%s] Google realtime: %d trendų", country.iso_code, len(df_rt))
        except Exception as exc:
            self.log.debug("[%s] Google realtime nepalaiko / klaida: %s",
                           country.iso_code, exc)

        return items
