"""YAML config loader with defaults, profiles, and interest matrix."""

from __future__ import annotations

import json
import os
from pathlib import Path

import yaml

from platoon.models import UserProfile

# -----------------------------------------------------------------------
# Shared categories injected into every profile
# -----------------------------------------------------------------------
SHARED_CATEGORIES = {
    "Trivia": {
        "keywords": [
            "TIL", "today I learned", "trivia", "weird", "surprising",
            "fascinating", "fun fact", "interesting", "bizarre", "unusual",
            "mind-blowing", "did you know", "history", "random",
        ],
        "weight": 0.9,
        "color": "#ec4899",
    },
    "General": {
        "keywords": [
            "world", "breaking", "crisis", "election", "policy",
            "climate", "environment", "health", "innovation",
        ],
        "weight": 0.7,
        "color": "#6b7280",
    },
}

# -----------------------------------------------------------------------
# Interest matrix: category -> Google News fallback queries
# Used when primary sources return too few items for a category.
# -----------------------------------------------------------------------
INTEREST_FALLBACKS = {
    # -- Shared / default --
    "AI":        ["artificial intelligence breakthroughs", "AI news today"],
    "Physics":   ["physics discovery", "space astronomy news"],
    "Business":  ["business economy startups", "tech industry news"],
    "Food":      ["food cooking restaurants", "new restaurant openings"],
    "Trivia":    ["weird interesting facts", "today I learned"],
    "General":   ["world news today", "interesting news"],
    # -- Eunseo --
    "Cats":      ["cats kittens viral", "cute cats news"],
    "Crafts":    ["crochet knitting sewing projects", "crafts DIY patterns"],
    "Korean":    ["Korea K-pop K-drama news", "Korean culture"],
    "Beauty":    ["skincare beauty science", "K-beauty trends"],
    "Chemistry": ["chemistry science discoveries", "chemistry news"],
}

# -----------------------------------------------------------------------
# Default sources — global feed configuration shared across all users.
# In library mode these are used when no config is provided.
# -----------------------------------------------------------------------
DEFAULT_SOURCES = {
    "google_news": {
        "enabled": True,
        "topics": ["science", "business", "technology"],
        "queries": [
            "AI artificial intelligence",
            "space physics discovery",
            "food restaurants trends",
        ],
        "max_items_per_query": 4,
    },
    "flipboard": {
        "enabled": True,
        "topics": ["science", "food", "technology", "space"],
        "max_items_per_topic": 3,
    },
    "trivia": {
        "enabled": True,
        "on_this_day": True,
        "random_facts": True,
        "max_items": 6,
    },
    "rss_feeds": {
        "enabled": True,
        "feeds": [
            {"url": "https://www.wired.com/feed/tag/ai/latest/rss", "label": "Wired AI"},
            {"url": "https://www.theverge.com/rss/ai-artificial-intelligence/index.xml", "label": "The Verge AI"},
            {"url": "https://feeds.arstechnica.com/arstechnica/technology-lab", "label": "Ars Technica"},
            {"url": "https://www.space.com/feeds/all", "label": "Space.com"},
            {"url": "https://feeds.bbci.co.uk/news/business/rss.xml", "label": "BBC Business"},
            {"url": "https://feeds.bbci.co.uk/news/science_and_environment/rss.xml", "label": "BBC Science"},
            {"url": "https://www.nasa.gov/feed/", "label": "NASA"},
            {"url": "https://www.bonappetit.com/feed/rss", "label": "Bon Appetit"},
            {"url": "https://www.eater.com/rss/index.xml", "label": "Eater"},
            {"url": "https://www.atlasobscura.com/feeds/latest", "label": "Atlas Obscura"},
            {"url": "https://www.sciencenews.org/feed", "label": "Science News"},
            {"url": "https://www.smithsonianmag.com/rss/latest_articles/", "label": "Smithsonian"},
            {"url": "https://www.newscientist.com/feed/home/", "label": "New Scientist"},
        ],
        "max_items_per_feed": 3,
    },
    "reddit": {
        "enabled": True,
        "subreddits": ["todayilearned", "interestingasfuck", "space", "food"],
        "min_score": 1000,
        "max_items": 4,
    },
    "hacker_news": {
        "enabled": True,
        "endpoint": "https://hacker-news.firebaseio.com/v0",
        "fetch_top_n": 20,
        "min_score": 200,
        "max_items": 5,
    },
    "lobsters": {"enabled": False},
    "arxiv": {"enabled": False},
    "hn_algolia": {"enabled": False},
    "github_trending": {"enabled": False},
    "papers_with_code": {"enabled": False},
    "semantic_scholar": {"enabled": False},
    "openalex": {"enabled": False},
}

DEFAULT_FETCHER = {
    "timeout": 15,
    "max_retries": 2,
    "retry_delay": 2,
    "rate_limit_delay": 0.5,
    "user_agent": "PlatoonBot/1.0 (news-digest)",
}

DEFAULT_OUTPUT = {
    "format": "html",
    "max_items_per_category": 5,
    "output_dir": "./output",
    "min_score": 0.1,
}

# -----------------------------------------------------------------------
# Default config
# -----------------------------------------------------------------------
DEFAULTS = {
    "fetcher": DEFAULT_FETCHER,
    "output": DEFAULT_OUTPUT,
    "sources": DEFAULT_SOURCES,
    "profiles": {
        "timeout": 15,
        "max_retries": 2,
        "retry_delay": 2,
        "rate_limit_delay": 0.5,
        "user_agent": "PlatoonBot/1.0 (news-digest)",
    },
    "output": {
        "format": "html",
        "max_items_per_category": 5,
        "output_dir": "./output",
        "min_score": 0.1,
    },
    "profiles": {
        # ==============================================================
        #  DEFAULT PROFILE
        #  Interests: AI, Physics, Business, Food, Trivia, General
        # ==============================================================
        "default": {
            "name": "Default",
            "interests": [
                "AI machine learning breakthroughs",
                "physics space quantum discoveries",
                "business startups economy",
                "food restaurants cooking recipes",
                "fun events trivia surprising facts",
            ],
            "categories": {
                "AI": {
                    "keywords": [
                        "AI", "LLM", "machine learning", "neural", "ChatGPT",
                        "agent", "transformer", "world model", "diffusion",
                        "deep learning", "robot", "autonomous",
                    ],
                    "weight": 1.5,
                    "color": "#3b82f6",
                },
                "Physics": {
                    "keywords": [
                        "physics", "quantum", "particle", "astrophysics", "fusion",
                        "dark matter", "cosmology", "black hole", "space", "NASA",
                        "telescope", "mars", "exoplanet", "gravitational",
                    ],
                    "weight": 1.3,
                    "color": "#8b5cf6",
                },
                "Business": {
                    "keywords": [
                        "startup", "funding", "enterprise", "revenue", "market",
                        "CEO", "acquisition", "IPO", "economy", "billion",
                        "valuation", "disruption", "investment",
                    ],
                    "weight": 1.0,
                    "color": "#22c55e",
                },
                "Food": {
                    "keywords": [
                        "food", "restaurant", "cooking", "recipe", "chef",
                        "cuisine", "dining", "meal", "flavor", "dish",
                        "kitchen", "baking", "wine", "coffee",
                    ],
                    "weight": 1.1,
                    "color": "#f97316",
                },
            },
            # Interest matrix — sources mapped to interests:
            #   AI       -> Google News, Wired AI, The Verge AI, Ars Technica, HN
            #   Physics  -> Google News, Space.com, BBC Science, NASA
            #   Business -> Google News, BBC Business
            #   Food     -> Google News, Flipboard, Bon Appetit, Eater
            #   Trivia   -> Wikimedia On This Day, Fun Facts, Reddit TIL
            #   General  -> Google News headlines, Flipboard
            "sources": {
                "google_news": {
                    "enabled": True,
                    "topics": ["science", "business", "technology"],
                    "queries": [
                        "AI artificial intelligence",
                        "space physics discovery",
                        "food restaurants trends",
                    ],
                    "max_items_per_query": 4,
                },
                "flipboard": {
                    "enabled": True,
                    "topics": ["science", "food", "technology", "space"],
                    "max_items_per_topic": 3,
                },
                "trivia": {
                    "enabled": True,
                    "on_this_day": True,
                    "random_facts": True,
                    "max_items": 6,
                },
                "rss_feeds": {
                    "enabled": True,
                    "feeds": [
                        {"url": "https://www.wired.com/feed/tag/ai/latest/rss", "label": "Wired AI"},
                        {"url": "https://www.theverge.com/rss/ai-artificial-intelligence/index.xml", "label": "The Verge AI"},
                        {"url": "https://feeds.arstechnica.com/arstechnica/technology-lab", "label": "Ars Technica"},
                        {"url": "https://www.space.com/feeds/all", "label": "Space.com"},
                        {"url": "https://feeds.bbci.co.uk/news/business/rss.xml", "label": "BBC Business"},
                        {"url": "https://feeds.bbci.co.uk/news/science_and_environment/rss.xml", "label": "BBC Science"},
                        {"url": "https://www.nasa.gov/feed/", "label": "NASA"},
                        {"url": "https://www.bonappetit.com/feed/rss", "label": "Bon Appetit"},
                        {"url": "https://www.eater.com/rss/index.xml", "label": "Eater"},
                        {"url": "https://www.atlasobscura.com/feeds/latest", "label": "Atlas Obscura"},
                        {"url": "https://www.sciencenews.org/feed", "label": "Science News"},
                        {"url": "https://www.smithsonianmag.com/rss/latest_articles/", "label": "Smithsonian"},
                        {"url": "https://www.newscientist.com/feed/home/", "label": "New Scientist"},
                    ],
                    "max_items_per_feed": 3,
                },
                "reddit": {
                    "enabled": True,
                    "subreddits": ["todayilearned", "interestingasfuck", "space", "food"],
                    "min_score": 1000,
                    "max_items": 4,
                },
                "hacker_news": {
                    "enabled": True,
                    "endpoint": "https://hacker-news.firebaseio.com/v0",
                    "fetch_top_n": 20,
                    "min_score": 200,
                    "max_items": 5,
                },
                "lobsters": {"enabled": False},
                "arxiv": {"enabled": False},
                "hn_algolia": {"enabled": False},
                "github_trending": {"enabled": False},
                "papers_with_code": {"enabled": False},
                "semantic_scholar": {"enabled": False},
                "openalex": {"enabled": False},
            },
        },

        # ==============================================================
        #  EUNSEO'S PROFILE
        #  Interests: Cats, Crafts, Korean, Food, Beauty, Chemistry, Trivia
        # ==============================================================
        "eunseo": {
            "name": "Eunseo",
            "interests": [
                "cats kittens feline care",
                "sewing crochet knitting crafts patterns",
                "Korean culture K-pop K-drama Korea",
                "Asian food Korean food recipes cooking",
                "chemistry skincare ingredients beauty",
                "fun trivia surprising facts",
            ],
            "categories": {
                "Cats": {
                    "keywords": [
                        "cat", "kitten", "feline", "meow", "purr", "tabby",
                        "calico", "siamese", "rescue", "adoption", "pet",
                    ],
                    "weight": 1.4,
                    "color": "#f472b6",
                },
                "Crafts": {
                    "keywords": [
                        "sewing", "crochet", "knitting", "yarn", "pattern",
                        "stitch", "fabric", "quilt", "embroidery", "handmade",
                        "craft", "fiber", "needle", "thread",
                    ],
                    "weight": 1.4,
                    "color": "#a78bfa",
                },
                "Korean": {
                    "keywords": [
                        "Korean", "Korea", "K-pop", "K-drama", "Seoul",
                        "hanbok", "hangul", "kdrama", "kpop", "BTS",
                        "kimchi", "hallyu",
                    ],
                    "weight": 1.3,
                    "color": "#38bdf8",
                },
                "Food": {
                    "keywords": [
                        "food", "recipe", "cooking", "restaurant", "cuisine",
                        "Asian food", "ramen", "bibimbap", "sushi", "dumpling",
                        "noodle", "tofu", "baking", "dessert", "matcha",
                    ],
                    "weight": 1.2,
                    "color": "#f97316",
                },
                "Beauty": {
                    "keywords": [
                        "skincare", "skin care", "beauty", "serum", "moisturizer",
                        "sunscreen", "retinol", "niacinamide", "hyaluronic",
                        "ingredient", "dermatology", "routine",
                    ],
                    "weight": 1.2,
                    "color": "#f0abfc",
                },
                "Chemistry": {
                    "keywords": [
                        "chemistry", "chemical", "molecule", "reaction",
                        "compound", "element", "periodic", "organic",
                        "synthesis", "polymer", "catalyst",
                    ],
                    "weight": 1.0,
                    "color": "#2dd4bf",
                },
            },
            # Interest matrix — sources mapped to Eunseo's interests:
            #   Cats      -> Google News, Flipboard, Reddit r/cats
            #   Crafts    -> Google News, Flipboard, Reddit r/crochet r/knitting r/sewing
            #   Korean    -> Google News, Soompi RSS, Koreaboo RSS, Korea Times RSS, Flipboard
            #   Food      -> Google News, Flipboard, Bon Appetit, Eater, Reddit r/koreanfood
            #   Beauty    -> Google News, Flipboard, Reddit r/AsianBeauty
            #   Chemistry -> Google News, Science News RSS, Reddit r/chemistry
            #   Trivia    -> Wikimedia On This Day, Fun Facts, Reddit TIL
            "sources": {
                "google_news": {
                    "enabled": True,
                    "queries": [
                        "cats kittens cute viral",
                        "K-pop K-drama Korean entertainment",
                        "crochet knitting sewing crafts",
                        "Korean food Asian food recipes",
                        "skincare beauty science trends",
                        "chemistry science discovery",
                    ],
                    "max_items_per_query": 3,
                },
                "flipboard": {
                    "enabled": True,
                    "topics": ["cats", "crafts", "kpop", "food", "skincare", "science"],
                    "max_items_per_topic": 3,
                },
                "trivia": {
                    "enabled": True,
                    "on_this_day": True,
                    "random_facts": True,
                    "max_items": 5,
                },
                "rss_feeds": {
                    "enabled": True,
                    "feeds": [
                        {"url": "https://www.soompi.com/feed", "label": "Soompi"},
                        {"url": "https://www.koreaboo.com/feed/", "label": "Koreaboo"},
                        {"url": "https://www.koreatimes.co.kr/www/rss/rss.xml", "label": "Korea Times"},
                        {"url": "https://www.bonappetit.com/feed/rss", "label": "Bon Appetit"},
                        {"url": "https://www.eater.com/rss/index.xml", "label": "Eater"},
                        {"url": "https://www.sciencenews.org/feed", "label": "Science News"},
                        {"url": "https://www.atlasobscura.com/feeds/latest", "label": "Atlas Obscura"},
                    ],
                    "max_items_per_feed": 3,
                },
                "reddit": {
                    "enabled": True,
                    "subreddits": [
                        "cats", "crochet", "knitting", "sewing",
                        "korea", "koreanfood", "AsianBeauty",
                        "todayilearned", "interestingasfuck", "chemistry",
                    ],
                    "min_score": 200,
                    "max_items": 4,
                },
                "hacker_news": {"enabled": False},
                "hn_algolia": {"enabled": False},
                "arxiv": {"enabled": False},
                "lobsters": {"enabled": False},
                "github_trending": {"enabled": False},
                "papers_with_code": {"enabled": False},
                "semantic_scholar": {"enabled": False},
                "openalex": {"enabled": False},
            },
        },
    },
}


# -----------------------------------------------------------------------
# Config loading
# -----------------------------------------------------------------------

def _deep_merge(base: dict, override: dict) -> dict:
    """Recursively merge override into base."""
    result = base.copy()
    for k, v in override.items():
        if k in result and isinstance(result[k], dict) and isinstance(v, dict):
            result[k] = _deep_merge(result[k], v)
        else:
            result[k] = v
    return result


def load_config(path: str | None = None) -> dict:
    """Load config from YAML, merged with defaults."""
    if not path:
        for candidate in ["config.yaml", "config.example.yaml"]:
            if Path(candidate).exists():
                path = candidate
                break
    if path and Path(path).exists():
        with open(path) as f:
            user_cfg = yaml.safe_load(f) or {}
        return _deep_merge(DEFAULTS, user_cfg)
    return DEFAULTS.copy()


def resolve_profile(config: dict, profile_name: str) -> dict:
    """Flatten a profile into a top-level config ready for the pipeline.

    Merges profile-specific interests/categories/sources into the config,
    and adds shared categories (Trivia, General) to every profile.
    """
    profiles = config.get("profiles", {})
    profile = profiles.get(profile_name)
    if not profile:
        available = list(profiles.keys())
        raise ValueError(f"Profile '{profile_name}' not found. Available: {available}")

    user_profile = UserProfile(
        profile_name=profile.get("name", profile_name),
        interests=profile.get("interests", []),
        categories={**SHARED_CATEGORIES, **profile.get("categories", {})},
    )

    resolved = {
        "fetcher": config.get("fetcher", {}),
        "output": config.get("output", {}),
        "sources": profile.get("sources", config.get("sources", DEFAULT_SOURCES)),
        **user_profile.to_config_dict(),
    }
    return resolved


# -----------------------------------------------------------------------
# API keys
# -----------------------------------------------------------------------

def resolve_keys() -> dict:
    """Resolve API keys from environment variables.

    Checks (in priority order):
      P8_PLATOON_KEYS  — JSON dict: {"tavily": "tvly-...", ...}
      P8_TAVILY_KEY    — single Tavily key
      TAVILY_API_KEY   — legacy Tavily key (backward compat)
    """
    keys: dict = {}

    raw = os.environ.get("P8_PLATOON_KEYS", "")
    if raw:
        try:
            keys = json.loads(raw)
        except json.JSONDecodeError:
            pass

    tavily = os.environ.get("P8_TAVILY_KEY", "") or os.environ.get("TAVILY_API_KEY", "")
    if tavily:
        keys.setdefault("tavily", tavily)

    return keys


# -----------------------------------------------------------------------
# Library-mode config resolution
# -----------------------------------------------------------------------

def resolve_for_user(user_metadata, config: dict | None = None) -> dict:
    """Build pipeline config from user metadata + global config.

    This is the library-mode entry point. User data (interests, categories)
    comes from the UserMetadata object; sources and fetcher settings come
    from the global config.

    Args:
        user_metadata: p8k8 UserMetadata object, UserProfile, or plain dict.
            Reads ``interests`` and ``categories`` fields.
        config: Global config with ``sources``, ``fetcher``, ``output``.
            If None, uses built-in defaults.

    Returns:
        Flat pipeline config dict ready for FeedProvider.run().
    """
    # Accept pydantic model or dict
    if hasattr(user_metadata, "model_dump"):
        meta = user_metadata.model_dump()
    elif isinstance(user_metadata, dict):
        meta = user_metadata
    else:
        raise TypeError(f"Expected dict or pydantic model, got {type(user_metadata)}")

    if config is None:
        config = {}

    interests = meta.get("interests") or []
    categories = {**SHARED_CATEGORIES, **(meta.get("categories") or {})}

    return {
        "fetcher": config.get("fetcher", DEFAULT_FETCHER),
        "output": config.get("output", DEFAULT_OUTPUT),
        "sources": config.get("sources", DEFAULT_SOURCES),
        "profile_name": meta.get("profile_name", "default"),
        "interests": interests,
        "categories": categories,
    }
