"""Check for newer CLI versions from appxen.ai/releases/latest.json."""

from __future__ import annotations

import json
import time
from pathlib import Path

import httpx

from appxen_cli import __version__

LATEST_URL = "https://appxen.ai/releases/latest.json"
CACHE_DIR = Path.home() / ".config" / "appxen"
CACHE_FILE = CACHE_DIR / "update-check.json"
CACHE_TTL = 86400  # 24 hours


def _parse_version(v: str) -> tuple[int, ...]:
    """Parse '0.2.2' into (0, 2, 2) for comparison."""
    return tuple(int(x) for x in v.strip().split("."))


def _read_cache() -> dict | None:
    """Read cached version info. Returns None on any error."""
    try:
        data = json.loads(CACHE_FILE.read_text())
        if time.time() - data.get("checked_at", 0) < CACHE_TTL:
            return data
    except Exception:
        pass
    return None


def _write_cache(version: str) -> None:
    """Write version to cache file. Errors silently ignored."""
    try:
        CACHE_DIR.mkdir(parents=True, exist_ok=True)
        CACHE_FILE.write_text(json.dumps({
            "latest": version,
            "checked_at": time.time(),
        }))
    except Exception:
        pass


def get_latest_version(use_cache: bool = True) -> str | None:
    """Fetch the latest published CLI version.

    Returns the version string (e.g. '0.3.0') or None on failure.
    Uses a 24h file cache by default; pass use_cache=False to skip.
    """
    if use_cache:
        cached = _read_cache()
        if cached:
            return cached.get("latest")

    try:
        resp = httpx.get(LATEST_URL, timeout=3.0, follow_redirects=True)
        resp.raise_for_status()
        version = resp.json()["version"]
        _write_cache(version)
        return version
    except Exception:
        return None


def is_update_available() -> tuple[bool, str | None]:
    """Check whether a newer version is available.

    Returns (True, '0.3.0') if newer, or (False, None) otherwise.
    Never raises — all errors return (False, None).
    """
    try:
        latest = get_latest_version()
        if latest is None:
            return False, None
        if _parse_version(latest) > _parse_version(__version__):
            return True, latest
        return False, None
    except Exception:
        return False, None
