from __future__ import annotations

from typing import List

from ..types import Candidate
from .base import BaseProvider


BASE_URL = "https://dblp.org/search/publ/api"


class DBLPProvider(BaseProvider):
    provider_name = "dblp"
    min_delay_seconds = 1.5
    timeout_seconds = 10.0
    max_results = 5

    def lookup_by_id(self, identifier: str, id_type: str) -> List[Candidate]:
        return []

    def search(self, query: str) -> List[Candidate]:
        params = {"q": query, "format": "json", "h": self.max_results}
        payload = self._request_json(BASE_URL, params=params)
        if payload["status_code"] != 200:
            return []
        data = payload["data"] or {}
        hits = data.get("result", {}).get("hits", {}).get("hit", [])
        candidates = []
        for hit in hits:
            info = hit.get("info", {})
            title = info.get("title")
            year = info.get("year")
            venue = info.get("venue")
            authors = _parse_authors(info.get("authors"))
            candidates.append(
                Candidate(
                    provider="dblp",
                    provider_id=info.get("key") or info.get("url") or "",
                    title=title,
                    authors=authors,
                    year=int(year) if str(year).isdigit() else None,
                    venue=venue,
                    ids={},
                    url=info.get("url"),
                    evidence={"source": "search"},
                )
            )
        return candidates


def _parse_authors(authors_field) -> list[str]:
    if not authors_field:
        return []
    author = authors_field.get("author") if isinstance(authors_field, dict) else None
    if isinstance(author, list):
        return [item.get("text") if isinstance(item, dict) else str(item) for item in author]
    if isinstance(author, dict):
        return [author.get("text", "")]
    if isinstance(author, str):
        return [author]
    return []
