# retoor <retoor@molodetz.nl>

import logging
import time

from devplacepy import stealth

logger = logging.getLogger(__name__)


class NewsFetcher:
    TTL_SECONDS = 1800

    def __init__(self, news_api: str):
        self.news_api = news_api
        self.articles: list[dict] = []
        self.fetched_at: float = 0.0

    def fetch(self) -> list[dict]:
        fresh = (
            self.articles and (time.monotonic() - self.fetched_at) < self.TTL_SECONDS
        )
        if fresh:
            return self.articles
        try:
            with stealth.stealth_sync_client(timeout=10) as client:
                resp = client.get(self.news_api)
                articles = resp.json().get("articles", [])
            if articles:
                self.articles = articles
                self.fetched_at = time.monotonic()
                logger.info("Fetched %d news articles", len(self.articles))
        except Exception as e:
            logger.warning("News fetch failed: %s", e)
        return self.articles
