"""IP-FD.net client for Python 3.8 or newer. Standard library only.

    from ipfd import IpFd
    ipfd = IpFd(api_key="your key")
    verdict = ipfd.check("203.0.113.7")      # {"allowed": False, "action": "block", "reasons": [...], "risk": 62, ...}
    risk = ipfd.risk("203.0.113.7")          # {"score": 62, "level": "high", "signals": ["vpn", "hosting"]}
    if ipfd.is_blocked("203.0.113.7"): ...

Calls time out after 1.5 seconds and fail open: when IP-FD.net cannot be reached, is_blocked() answers False.
Answers are cached in memory for 5 minutes.
"""
import json
import threading
import time
import urllib.error
import urllib.parse
import urllib.request


class IpFd:
    def __init__(self, api_key="", base_url="https://ip-fd.net", timeout=1.5, cache_seconds=300, max_cache=5000):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.cache_seconds = cache_seconds
        self.max_cache = max_cache
        self._cache = {}
        self._lock = threading.Lock()

    def _get(self, path):
        now = time.time()
        with self._lock:
            hit = self._cache.get(path)
            if hit and hit[0] > now:
                return hit[1]
        headers = {"Accept": "application/json", "User-Agent": "ipfd-python/1.0"}
        if self.api_key:
            headers["X-API-Key"] = self.api_key
        request = urllib.request.Request(self.base_url + path, headers=headers)
        with urllib.request.urlopen(request, timeout=self.timeout) as response:
            value = json.loads(response.read().decode("utf-8"))
        with self._lock:
            if len(self._cache) >= self.max_cache:
                self._cache.pop(next(iter(self._cache)))
            self._cache[path] = (now + self.cache_seconds, value)
        return value

    def check(self, ip):
        """Allow or block by your account's access rules."""
        return self._get("/api/v1/check/" + urllib.parse.quote(str(ip), safe=""))

    def risk(self, ip):
        """{"score": 0-100, "level": "low|moderate|high|very_high", "signals": [...]}"""
        data = self._get("/api/v1/ip/" + urllib.parse.quote(str(ip), safe="") + "/risk")
        return data.get("value", data)

    def lookup(self, ip):
        """The full lookup of an address."""
        return self._get("/api/v1/ip/" + urllib.parse.quote(str(ip), safe=""))

    def is_blocked(self, ip, max_risk=None):
        """True when your access rules block the address (or, with max_risk, when its risk score is at least that). Fails open."""
        try:
            if max_risk is not None:
                return self.risk(ip).get("score", 0) >= max_risk
            return self.check(ip).get("allowed") is False
        except (urllib.error.URLError, TimeoutError, ValueError, OSError):
            return False
