# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Google Trends Skill

Discover trending searches, interest over time, and related queries.
Uses the Google Trends API (v1alpha, launched July 2025).

Setup:
    GOOGLE_TRENDS_API_KEY=your_key   (Google Cloud API key with Trends API enabled)

API: https://trends.googleapis.com/v1alpha/
"""

import logging

from familiar.core.api_cache import cached
from familiar.skills._api_utils import (
    APIError,
    api_get,
    get_env,
)

logger = logging.getLogger(__name__)

BASE_URL = "https://trends.googleapis.com/v1alpha"


def _api_key() -> str:
    return get_env("GOOGLE_TRENDS_API_KEY") or ""


# ---------------------------------------------------------------------------
# Tool handlers
# ---------------------------------------------------------------------------


def trending_now(data: dict) -> str:
    """Get currently trending searches for a region."""
    key = _api_key()
    if not key:
        return (
            "Google Trends API key not configured.\n"
            "Set GOOGLE_TRENDS_API_KEY with a Google Cloud API key.\n"
            "Enable the Google Trends API in your Cloud Console."
        )

    geo = data.get("geo", "US").upper()

    try:
        result = _trending_cached(geo)

        trending = result.get("trendingSearches", result.get("trending_searches", []))
        if not trending:
            return f"No trending searches found for {geo}."

        lines = [f"**Trending Now ({geo}):**", ""]

        for i, item in enumerate(trending[:20], 1):
            # Handle both possible response shapes
            if isinstance(item, dict):
                title = item.get("title", item.get("query", str(item)))
                traffic = item.get("formattedTraffic", item.get("traffic", ""))
                related = item.get("relatedQueries", [])
            else:
                title = str(item)
                traffic = ""
                related = []

            line = f"{i}. **{title}**"
            if traffic:
                line += f" — {traffic} searches"
            lines.append(line)

            if related and isinstance(related, list):
                rel_text = ", ".join(str(r) for r in related[:3])
                lines.append(f"   Related: {rel_text}")

        return "\n".join(lines)

    except APIError as e:
        return str(e)
    except Exception as e:
        logger.error("Google Trends trending error: %s", e)
        return f"Error fetching trends: {e}"


@cached(prefix="gtrends_trending", ttl=1800)
def _trending_cached(geo: str) -> dict:
    return api_get(
        f"{BASE_URL}/trending",
        params={"key": _api_key(), "geo": geo},
        service_name="Google Trends",
    )


def interest_over_time(data: dict) -> str:
    """Get search interest over time for given terms."""
    key = _api_key()
    if not key:
        return (
            "Google Trends API key not configured.\n"
            "Set GOOGLE_TRENDS_API_KEY with a Google Cloud API key."
        )

    terms = data.get("terms", [])
    if isinstance(terms, str):
        terms = [t.strip() for t in terms.split(",") if t.strip()]

    if not terms:
        return "Please provide one or more search terms to analyze."

    if len(terms) > 5:
        return "Maximum 5 terms can be compared at once."

    geo = data.get("geo", "US").upper()
    timeframe = data.get("timeframe", "today 12-m")

    try:
        result = _interest_cached(tuple(terms), geo, timeframe)

        timeline = result.get("timelineData", result.get("timeline_data", []))
        if not timeline:
            return f"No interest data found for: {', '.join(terms)}"

        lines = [
            f"**Interest Over Time: {', '.join(terms)}**",
            f"Region: {geo} | Period: {timeframe}",
            "",
        ]

        # Build a simple text chart
        # Show last 12 data points for brevity
        show_points = timeline[-12:] if len(timeline) > 12 else timeline

        for point in show_points:
            time_label = point.get("formattedTime", point.get("date", ""))
            values = point.get("value", point.get("values", []))

            if isinstance(values, list):
                val_strs = []
                for j, v in enumerate(values):
                    val = v if isinstance(v, (int, float)) else v.get("value", 0)
                    term_label = terms[j] if j < len(terms) else f"Term {j + 1}"
                    bar = "#" * (int(val) // 5) if isinstance(val, (int, float)) else ""
                    val_strs.append(f"{term_label}: {val} {bar}")
                lines.append(f"  {time_label}")
                for vs in val_strs:
                    lines.append(f"    {vs}")
            else:
                val = values if isinstance(values, (int, float)) else 0
                bar = "#" * (int(val) // 5)
                lines.append(f"  {time_label}: {val} {bar}")

        lines.append("")
        lines.append("_Values are relative (0-100). 100 = peak popularity._")

        return "\n".join(lines)

    except APIError as e:
        return str(e)
    except Exception as e:
        logger.error("Google Trends interest error: %s", e)
        return f"Error fetching interest data: {e}"


@cached(prefix="gtrends_interest", ttl=3600)
def _interest_cached(terms: tuple, geo: str, timeframe: str) -> dict:
    params = {
        "key": _api_key(),
        "geo": geo,
        "timeframe": timeframe,
    }
    # API accepts multiple terms as repeated 'term' params
    # httpx handles list values as repeated params
    params["terms"] = ",".join(terms)

    return api_get(
        f"{BASE_URL}/trends:query",
        params=params,
        service_name="Google Trends",
    )


def related_queries(data: dict) -> str:
    """Get queries related to a search term."""
    key = _api_key()
    if not key:
        return (
            "Google Trends API key not configured.\n"
            "Set GOOGLE_TRENDS_API_KEY with a Google Cloud API key."
        )

    term = data.get("term", "").strip()
    if not term:
        return "Please provide a search term."

    geo = data.get("geo", "US").upper()

    try:
        result = _related_cached(term, geo)

        top = result.get("top", result.get("topQueries", []))
        rising = result.get("rising", result.get("risingQueries", []))

        if not top and not rising:
            return f"No related queries found for '{term}'."

        lines = [f"**Related Queries: {term}** ({geo})", ""]

        if top:
            lines.append("**Top (consistently popular):**")
            for i, q in enumerate(top[:10], 1):
                if isinstance(q, dict):
                    query = q.get("query", q.get("title", str(q)))
                    value = q.get("value", q.get("formattedValue", ""))
                else:
                    query = str(q)
                    value = ""
                line = f"  {i}. {query}"
                if value:
                    line += f" ({value})"
                lines.append(line)
            lines.append("")

        if rising:
            lines.append("**Rising (gaining popularity):**")
            for i, q in enumerate(rising[:10], 1):
                if isinstance(q, dict):
                    query = q.get("query", q.get("title", str(q)))
                    value = q.get("value", q.get("formattedValue", ""))
                else:
                    query = str(q)
                    value = ""
                line = f"  {i}. {query}"
                if value:
                    line += f" ({value})"
                lines.append(line)

        return "\n".join(lines)

    except APIError as e:
        return str(e)
    except Exception as e:
        logger.error("Google Trends related error: %s", e)
        return f"Error fetching related queries: {e}"


@cached(prefix="gtrends_related", ttl=3600)
def _related_cached(term: str, geo: str) -> dict:
    return api_get(
        f"{BASE_URL}/relatedQueries",
        params={"key": _api_key(), "term": term, "geo": geo},
        service_name="Google Trends",
    )


# ---------------------------------------------------------------------------
# Tool definitions
# ---------------------------------------------------------------------------

TOOLS = [
    {
        "name": "trending_now",
        "description": (
            "Get currently trending searches for a region."
            " Shows what people are searching for right now."
            " Requires GOOGLE_TRENDS_API_KEY."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "geo": {
                    "type": "string",
                    "description": "Region code (e.g., 'US', 'GB', 'DE')",
                    "default": "US",
                },
            },
        },
        "handler": trending_now,
        "category": "google_trends",
    },
    {
        "name": "interest_over_time",
        "description": (
            "Track search interest for terms over time."
            " Compare up to 5 terms. Values are relative (0-100)."
            " Useful for market research and trend analysis."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "terms": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Search terms to analyze (max 5)",
                },
                "geo": {
                    "type": "string",
                    "description": "Region code (default 'US')",
                    "default": "US",
                },
                "timeframe": {
                    "type": "string",
                    "description": (
                        "Time range: 'today 1-m', 'today 3-m', 'today 12-m',"
                        " 'today 5-y', or 'YYYY-MM-DD YYYY-MM-DD'"
                    ),
                    "default": "today 12-m",
                },
            },
            "required": ["terms"],
        },
        "handler": interest_over_time,
        "category": "google_trends",
    },
    {
        "name": "related_queries",
        "description": (
            "Find queries related to a search term."
            " Shows both top (consistently popular) and rising"
            " (gaining popularity) related searches."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "term": {
                    "type": "string",
                    "description": "Search term to find related queries for",
                },
                "geo": {
                    "type": "string",
                    "description": "Region code (default 'US')",
                    "default": "US",
                },
            },
            "required": ["term"],
        },
        "handler": related_queries,
        "category": "google_trends",
    },
]
