"""Papers with Code — REST API."""

from __future__ import annotations

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


def fetch_papers_with_code(cfg: dict, fetcher: Fetcher) -> list[Item]:
    endpoint = cfg.get("endpoint", "https://paperswithcode.com/api/v1/papers/")
    max_items = cfg.get("max_items", 10)

    print("Fetching Papers with Code...")
    resp = fetcher.get(endpoint, params={"ordering": "-published", "items_per_page": max_items})
    if not resp:
        return []

    data = resp.json()
    results = data.get("results", [])
    items = []
    for p in results:
        arxiv_id = p.get("arxiv_id", "")
        url = f"https://arxiv.org/abs/{arxiv_id}" if arxiv_id else p.get("url_abs", "")
        has_code = bool(p.get("github_link"))
        items.append(Item(
            title=p.get("title", ""),
            url=url,
            source="Papers with Code",
            summary=(p.get("abstract") or "")[:400],
            tags=["has_code"] if has_code else [],
            engagement={
                "stars": 1 if has_code else 0,
            },
        ))

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