"""Semantic Scholar — Graph API."""

from __future__ import annotations

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


def fetch_semantic_scholar(cfg: dict, fetcher: Fetcher) -> list[Item]:
    endpoint = cfg.get("endpoint", "https://api.semanticscholar.org/graph/v1/paper/search")
    max_items = cfg.get("max_items", 10)
    queries = cfg.get("queries", [])
    items = []

    for query in queries:
        print(f"Fetching Semantic Scholar [{query[:40]}]...")
        params = {
            "query": query,
            "fields": "title,abstract,url,year,citationCount",
            "limit": max_items,
        }
        resp = fetcher.get(endpoint, params=params)
        if not resp:
            continue
        data = resp.json()
        for p in data.get("data", []):
            items.append(Item(
                title=p.get("title", ""),
                url=p.get("url", ""),
                source="Semantic Scholar",
                summary=(p.get("abstract") or "")[:400],
                engagement={
                    "citations": p.get("citationCount", 0),
                },
            ))

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