"""PhotoPick app update check via everflow-api-server release metadata."""

from __future__ import annotations

import platform
import re
from typing import Any, Dict, Optional, Tuple

from .. import config
from . import everflow_client

_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)")


def _parse_version(value: str) -> Tuple[int, int, int]:
    match = _VERSION_RE.match((value or "").strip())
    if not match:
        return (0, 0, 0)
    return (int(match.group(1)), int(match.group(2)), int(match.group(3)))


def compare_versions(current: str, latest: str) -> int:
    """Return -1 if current < latest, 0 if equal, 1 if current > latest."""
    cur = _parse_version(current)
    lat = _parse_version(latest)
    if cur < lat:
        return -1
    if cur > lat:
        return 1
    return 0


def _download_url_for_arch(release: Dict[str, Any]) -> Optional[str]:
    downloads = release.get("downloads") or {}
    machine = platform.machine().lower()
    if machine in ("arm64", "aarch64"):
        return downloads.get("arm64") or downloads.get("intel")
    return downloads.get("intel") or downloads.get("arm64")


def check_update() -> Dict[str, Any]:
    current = config.app_version()
    try:
        release = everflow_client.fetch_latest_release()
    except everflow_client.LicenseApiError as exc:
        return {
            "ok": False,
            "current_version": current,
            "error": str(exc),
        }

    latest = str(release.get("version") or "0.0.0")
    update_available = compare_versions(current, latest) < 0
    return {
        "ok": True,
        "current_version": current,
        "latest_version": latest,
        "update_available": update_available,
        "release_notes": release.get("release_notes") or "",
        "purchase_url": release.get("purchase_url"),
        "download_url": _download_url_for_arch(release) if update_available else None,
        "downloads": release.get("downloads") or {},
        "published_at": release.get("published_at"),
    }
