"""IETF Datatracker adapter — delegates to existing Fetcher."""

from __future__ import annotations

from ..config import Config
from ..fetcher import Fetcher
from ..models import Draft
from .base import SourceDocument


class IETFFetcher:
    """IETF Datatracker adapter wrapping the existing Fetcher class."""

    def __init__(self, config: Config | None = None):
        self.config = config or Config.load()
        self._fetcher = Fetcher(self.config)

    def search(
        self, keywords: list[str], since: str | None = None
    ) -> list[SourceDocument]:
        """Search Datatracker, convert Draft -> SourceDocument."""
        drafts = self._fetcher.search_drafts(keywords=keywords, since=since)
        return [self._draft_to_doc(d) for d in drafts]

    def download_text(self, doc: SourceDocument) -> str | None:
        """Download full text for a SourceDocument."""
        draft = self._doc_to_draft(doc)
        return self._fetcher.download_full_text(draft)

    def close(self) -> None:
        self._fetcher.close()

    @staticmethod
    def _draft_to_doc(draft: Draft) -> SourceDocument:
        return SourceDocument(
            name=draft.name,
            title=draft.title,
            abstract=draft.abstract,
            source="ietf",
            source_id=str(draft.dt_id) if draft.dt_id else "",
            source_url=draft.datatracker_url,
            full_text=draft.full_text,
            time=draft.time or "",
            doc_status="active",
            extra={
                "rev": draft.rev,
                "pages": draft.pages,
                "words": draft.words,
                "group": draft.group,
                "group_uri": draft.group_uri,
                "expires": draft.expires,
                "ad": draft.ad,
                "shepherd": draft.shepherd,
                "states": draft.states,
                "fetched_at": draft.fetched_at,
            },
        )

    @staticmethod
    def _doc_to_draft(doc: SourceDocument) -> Draft:
        extra = doc.extra or {}
        return Draft(
            name=doc.name,
            rev=extra.get("rev", "00"),
            title=doc.title,
            abstract=doc.abstract,
            time=doc.time,
            dt_id=int(doc.source_id) if doc.source_id else None,
            pages=extra.get("pages"),
            words=extra.get("words"),
            group=extra.get("group"),
            group_uri=extra.get("group_uri"),
            expires=extra.get("expires"),
            ad=extra.get("ad"),
            shepherd=extra.get("shepherd"),
            states=extra.get("states", []),
            full_text=doc.full_text,
            fetched_at=extra.get("fetched_at"),
            source="ietf",
            source_id=doc.source_id,
            source_url=doc.source_url,
        )
