"""
News Brief — fetch top headlines + topic-specific news via DuckDuckGo.

Topics of interest are stored at ~/.familiar/data/news_topics.json:
{"topics": ["climate", "nonprofit law", "trans rights"]}
"""

from __future__ import annotations

import json
import logging
from pathlib import Path

logger = logging.getLogger(__name__)


def _topics_path() -> Path:
    try:
        from familiar.core.paths import DATA_DIR

        return DATA_DIR / "news_topics.json"
    except ImportError:
        return Path.home() / ".familiar" / "data" / "news_topics.json"


def load_topics() -> list[str]:
    path = _topics_path()
    if not path.exists():
        return []
    try:
        return json.loads(path.read_text()).get("topics", [])
    except Exception:
        return []


def save_topics(topics: list[str]) -> None:
    path = _topics_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps({"topics": topics}, indent=2))


def add_topic(topic: str) -> str:
    topics = load_topics()
    topic = topic.strip().lower()
    if topic in topics:
        return f'Already tracking "{topic}"'
    if len(topics) >= 5:
        return f"Already tracking 5 topics (the maximum). Remove one first: {', '.join(topics)}"
    topics.append(topic)
    save_topics(topics)
    return f'Now tracking news topic: "{topic}"'


def remove_topic(topic: str) -> str:
    topics = load_topics()
    topic = topic.strip().lower()
    if topic not in topics:
        return f'Topic "{topic}" not found.'
    topics = [t for t in topics if t != topic]
    save_topics(topics)
    return f'Removed news topic: "{topic}"'


def _ddg_news(query: str, max_results: int = 5) -> list[dict]:
    """Fetch news results via duckduckgo_search (ddgs package)."""
    try:
        try:
            from ddgs import DDGS
        except ImportError:
            from duckduckgo_search import DDGS  # older package name

        with DDGS() as d:
            raw = d.news(query, max_results=max_results)
        return [
            {
                "title": r.get("title", ""),
                "source": r.get("source", ""),
                "url": r.get("url", ""),
                "date": r.get("date", ""),
                "body": r.get("body", ""),
            }
            for r in raw
        ]
    except Exception as e:
        logger.debug("DDG news failed for %q: %s", query, e)
        return []


def get_news_brief(max_top: int = 5, max_per_topic: int = 2) -> dict:
    """Return structured news data for the briefing.

    Returns:
        {
          "top": [{title, source, url, date}],           # general top news
          "topics": {topic: [{title, source, url}]},     # per-topic results
        }
    """
    result: dict = {"top": [], "topics": {}}

    # Top headlines
    result["top"] = _ddg_news("top news today", max_results=max_top)

    # Per-topic news
    for topic in load_topics():
        items = _ddg_news(f"{topic} news", max_results=max_per_topic)
        if items:
            result["topics"][topic] = items

    return result
