# Copyright (c) CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#

from typing import Any

from packaging import version

from src.utils.console import print_info, print_warning


class VersionInfo:
    """
    Handles CLI version information and comparison with backend versions.
    """

    def __init__(self, local_version: str, backend_version: str | None = None):
        """
        Initialize the version info handler.

        Args:
            local_version: The local CLI version string
            backend_version: The backend version string (if available)
        """
        self.local_version = local_version
        self.backend_version = backend_version
        self.backend_available = backend_version is not None

        # Parse versions
        self.local_parsed = version.parse(local_version)
        self.backend_parsed = version.parse(backend_version) if backend_version else None

    def is_compatible(self) -> bool:
        """
        Check if local and backend versions are compatible.

        Returns:
            True if versions are compatible or backend is unavailable
        """
        if not self.backend_available:
            return True

        return self.local_parsed >= self.backend_parsed

    def get_status(self) -> dict[str, Any]:
        """
        Get version status information.

        Returns:
            Dict with version status
        """
        return {
            "local_version": self.local_version,
            "backend_version": self.backend_version,
            "backend_available": self.backend_available,
            "compatible": self.is_compatible(),
        }


def cli_version_info(local_version: str, backend_info: dict[str, Any]) -> tuple[bool, dict[str, Any]]:
    """
    Checks CloudZero CLI version against backend version.

    Args:
        local_version: Local CLI version string
        backend_info: Backend version information

    Returns:
        Tuple of (compatible flag, status information)
    """
    backend_version = backend_info.get("cli_min_version")
    version_handler = VersionInfo(local_version, backend_version)

    status = version_handler.get_status()
    compatible = status["compatible"]

    if not backend_version:
        print_info("Backend version information not available, skipping version check.")
    elif not compatible:
        print_warning(
            f"⚠️  WARNING: Your CLI version ({local_version}) is older than the minimum required version ({backend_version}) by the backend."
        )
        print_warning("Please update your CLI to avoid compatibility issues.")

    return compatible, status
