"""Render scored items to HTML or JSON."""

from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path

from jinja2 import Environment, FileSystemLoader

from platoon.models import Item


def _group_by_category(items: list[Item]) -> dict[str, list[Item]]:
    groups: dict[str, list[Item]] = {}
    for item in items:
        groups.setdefault(item.category, []).append(item)
    return groups


def render_html(items: list[Item], config: dict) -> str:
    """Render items to a self-contained HTML file."""
    template_dir = Path(__file__).parent / "templates"
    env = Environment(loader=FileSystemLoader(str(template_dir)), autoescape=True)
    template = env.get_template("feed.html")

    categories = config.get("categories", {})
    cat_colors = {name: cfg.get("color", "#6b7280") for name, cfg in categories.items()}

    source_colors = {
        "Hacker News": "#ff6600",
        "arXiv": "#b31b1b",
        "Lobsters": "#9c3328",
        "Papers with Code": "#21a0a0",
        "Semantic Scholar": "#1857b6",
        "OpenAlex": "#e84393",
        "Reddit": "#ff4500",
        "GitHub Trending": "#6e40c9",
        "HN Algolia": "#ff8c00",
        "Google News": "#4285f4",
        "Flipboard": "#e12828",
        "On This Day": "#636efa",
        "Fun Fact": "#10b981",
        "Web Search": "#7c3aed",
    }

    groups = _group_by_category(items)
    all_categories = ["All"] + list(groups.keys())

    profile_name = config.get("profile_name", "Feed")

    return template.render(
        items=items,
        groups=groups,
        all_categories=all_categories,
        cat_colors=cat_colors,
        source_colors=source_colors,
        date=datetime.now().strftime("%A, %d %B %Y"),
        total=len(items),
        profile_name=profile_name,
    )


def render_json(items: list[Item]) -> str:
    """Render items to JSON."""
    return json.dumps(
        {
            "date": datetime.now().strftime("%Y-%m-%d"),
            "total": len(items),
            "items": [i.to_dict() for i in items],
        },
        indent=2,
    )


def save_output(content: str, fmt: str, config: dict, suffix: str = "") -> Path:
    """Save rendered output to file."""
    out_dir = Path(config.get("output", {}).get("output_dir", "./output"))
    out_dir.mkdir(parents=True, exist_ok=True)
    date_str = datetime.now().strftime("%Y-%m-%d")
    ext = "html" if fmt == "html" else "json"
    name = f"{date_str}-{suffix}" if suffix else date_str
    path = out_dir / f"{name}.{ext}"
    path.write_text(content)
    print(f"  Output saved to {path}")
    return path
