from __future__ import annotations

from dataclasses import dataclass, field
from typing import Callable


@dataclass
class BaselinePriceCache:
    ttl_seconds: int = 300
    values: dict[str, tuple[float, float]] = field(default_factory=dict)

    def get(self, coin: str, *, now_ts: float, fetcher: Callable[[str], float]) -> float:
        key = str(coin).upper()
        cached = self.values.get(key)
        if cached and now_ts - cached[0] <= self.ttl_seconds:
            return cached[1]
        try:
            value = float(fetcher(key))
        except Exception:
            if cached:
                return cached[1]
            raise
        self.values[key] = (now_ts, value)
        return value


def should_log_error(key: str, *, now_ts: float, last_log: dict[str, float], interval_seconds: int) -> bool:
    previous = last_log.get(key)
    if previous is not None and now_ts - previous < interval_seconds:
        return False
    last_log[key] = now_ts
    return True
