"""Check PyPI for newer fliiq versions. Background, cached, non-blocking."""

import json
import os
import threading
import time
import urllib.request

from fliiq.runtime.config import GLOBAL_DIR

CACHE_PATH = GLOBAL_DIR / ".update_cache"
CACHE_TTL = 86400  # 24 hours
PYPI_URL = "https://pypi.org/pypi/fliiq/json"


def get_current_version() -> str:
    from fliiq import __version__
    return __version__


def _is_newer(latest: str, current: str) -> bool:
    try:
        latest_parts = tuple(int(x) for x in latest.split("."))
        current_parts = tuple(int(x) for x in current.split("."))
        return latest_parts > current_parts
    except (ValueError, AttributeError):
        return False


def _fetch_latest_version() -> str | None:
    try:
        req = urllib.request.Request(PYPI_URL, headers={"Accept": "application/json"})
        with urllib.request.urlopen(req, timeout=3) as resp:
            data = json.loads(resp.read())
            return data["info"]["version"]
    except Exception:
        return None


def _write_cache(latest_version: str | None) -> None:
    try:
        CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
        payload = {"checked_at": time.time(), "latest_version": latest_version}
        CACHE_PATH.write_text(json.dumps(payload))
    except Exception:
        pass


def _cache_is_fresh() -> bool:
    try:
        data = json.loads(CACHE_PATH.read_text())
        return (time.time() - data["checked_at"]) < CACHE_TTL
    except Exception:
        return False


def check_update_cached() -> str | None:
    """Read cache and return notification string if update available."""
    try:
        data = json.loads(CACHE_PATH.read_text())
        latest = data.get("latest_version")
        if not latest:
            return None
        current = get_current_version()
        if _is_newer(latest, current):
            return f"fliiq {latest} available (you have {current}). Run: pip install --upgrade fliiq"
        return None
    except Exception:
        return None


def _background_check() -> None:
    latest = _fetch_latest_version()
    _write_cache(latest)


def trigger_update_check() -> None:
    """Fire-and-forget background thread to check PyPI and write cache."""
    if os.environ.get("FLIIQ_NO_UPDATE_CHECK") == "1":
        return
    if _cache_is_fresh():
        return
    t = threading.Thread(target=_background_check, daemon=True)
    t.start()
