"""Lobsters — JSON feed."""

from __future__ import annotations

from platoon.models import Item
from platoon.fetcher import Fetcher


def fetch_lobsters(cfg: dict, fetcher: Fetcher) -> list[Item]:
    endpoint = cfg.get("endpoint", "https://lobste.rs/newest.json")
    tag_filter = set(cfg.get("tags_filter", []))
    max_items = cfg.get("max_items", 20)

    print("Fetching Lobsters...")
    resp = fetcher.get(endpoint)
    if not resp:
        return []

    stories = resp.json()
    items = []
    for s in stories:
        if len(items) >= max_items:
            break
        tags = set(s.get("tags", []))
        if tag_filter and not tags.intersection(tag_filter):
            continue
        items.append(Item(
            title=s.get("title", ""),
            url=s.get("url") or s.get("short_id_url", ""),
            source="Lobsters",
            summary=s.get("description", "")[:400],
            tags=list(tags),
            engagement={
                "upvotes": s.get("score", 0),
                "comments": s.get("comment_count", 0),
            },
        ))

    print(f"  -> {len(items)} items")
    return items
