"""Version management and update checker."""

from __future__ import annotations

import json
import urllib.error
import urllib.request
from functools import lru_cache

from packaging import version

from .. import __version__

PYPI_API_URL = "https://pypi.org/pypi/replymarketing/json"


@lru_cache(maxsize=1)
def get_latest_version() -> str | None:
    """Fetch the latest version from PyPI."""
    try:
        req = urllib.request.Request(
            PYPI_API_URL,
            headers={"User-Agent": "ReplyMarketing-CLI/VersionChecker"},
        )
        with urllib.request.urlopen(req, timeout=5) as response:
            data = json.loads(response.read().decode("utf-8"))
            return data["info"]["version"]
    except (urllib.error.URLError, json.JSONDecodeError, KeyError):
        return None


def get_current_version() -> str:
    """Get the current installed version."""
    return __version__


def check_for_update() -> tuple[bool, str, str]:
    """Check if an update is available.

    Returns:
        Tuple of (update_available, current_version, latest_version)
    """
    current = get_current_version()
    latest = get_latest_version()

    if latest is None:
        return False, current, current

    try:
        current_v = version.parse(current)
        latest_v = version.parse(latest)
        update_available = latest_v > current_v
    except version.InvalidVersion:
        # Fallback to string comparison
        update_available = latest != current

    return update_available, current, latest


def get_update_command() -> str:
    """Get the recommended update command based on installation method."""
    # Check if installed via uv
    import shutil

    if shutil.which("uv"):
        return "uv tool upgrade replymarketing"

    # Fallback to pip
    return "pip install --upgrade replymarketing"
