"""
Trust resolver — fetches trust scores for agents.

Default: queries ai.wot REST API.
Pluggable: provide your own resolver function.
"""

from __future__ import annotations

import time
from typing import Callable, Awaitable, Optional

import httpx


class TrustResolver:
    """Resolve trust scores for agents."""

    def __init__(
        self,
        *,
        resolver: Optional[Callable[[str], Awaitable[Optional[int]]]] = None,
        cache_ttl_s: int = 300,
    ):
        self._resolver = resolver
        self._cache_ttl_s = cache_ttl_s
        self._cache: dict[str, tuple[Optional[int], float]] = {}

    async def get_score(self, agent_id: str) -> Optional[int]:
        if self._resolver is None:
            return None

        # Check cache
        cached = self._cache.get(agent_id)
        if cached and (time.time() - cached[1]) < self._cache_ttl_s:
            return cached[0]

        try:
            score = await self._resolver(agent_id)
            self._cache[agent_id] = (score, time.time())
            return score
        except Exception:
            return cached[0] if cached else None

    def clear_cache(self) -> None:
        self._cache.clear()

    def stats(self) -> dict:
        return {"cache_size": len(self._cache)}


def static_resolver(scores: dict[str, int]) -> TrustResolver:
    """Create a resolver from a static map of scores."""

    async def _resolve(agent_id: str) -> Optional[int]:
        return scores.get(agent_id)

    return TrustResolver(resolver=_resolve)


def api_resolver(api_url: str, timeout: float = 5.0) -> TrustResolver:
    """
    Create a resolver that queries the ai.wot REST API.

    Args:
        api_url: Base URL (e.g. https://wot.jeletor.cc)
        timeout: Request timeout in seconds
    """

    async def _resolve(agent_id: str) -> Optional[int]:
        try:
            async with httpx.AsyncClient(timeout=timeout) as client:
                resp = await client.get(f"{api_url}/v1/score/{agent_id}")
                if resp.status_code == 200:
                    data = resp.json()
                    score = data.get("score")
                    return int(score) if score is not None else None
        except Exception:
            pass
        return None

    return TrustResolver(resolver=_resolve)
