import logging

from pydantic import ValidationError

from labels.advisories import images as images_advisories
from labels.advisories import roots as roots_advisories
from labels.model.advisories import Advisory
from labels.model.ecosystem_data.alpine import ApkDBEntry
from labels.model.ecosystem_data.arch import AlpmDBEntry
from labels.model.ecosystem_data.debian import DpkgDBEntry
from labels.model.ecosystem_data.redhat import RpmDBEntry
from labels.model.package import Ecosystem, Package
from labels.parsers.cataloger.utils import extract_distro_info
from labels.utils.strings import format_exception

LOGGER = logging.getLogger(__name__)


ROOT_TYPES: set[Ecosystem] = {
    Ecosystem.NPM,
    Ecosystem.PUB,
    Ecosystem.NUGET,
    Ecosystem.MAVEN,
    Ecosystem.PACKAGIST,
    Ecosystem.PYPI,
    Ecosystem.RUBYGEMS,
    Ecosystem.GO,
    Ecosystem.SWIFTURL,
}

IMAGES_TYPES: set[Ecosystem] = {
    Ecosystem.ALPM,
    Ecosystem.DEBIAN,
    Ecosystem.ALPINE,
    Ecosystem.RPM,
}


def update_root_advisories(package: Package) -> list[Advisory]:
    safe_versions = roots_advisories.get_safe_versions(package.ecosystem, package.name)
    package.safe_versions = safe_versions
    return roots_advisories.get_vulnerabilities(
        package.ecosystem,
        package.name,
        package.version,
        safe_versions,
    )


def _get_upstream_info(package: Package) -> tuple[str | None, str | None]:
    if (
        package.ecosystem == Ecosystem.ALPINE
        and isinstance(package.ecosystem_data, ApkDBEntry)
        and package.ecosystem_data
        and package.ecosystem_data.origin_package
    ):
        return package.ecosystem_data.origin_package, package.version

    if (
        package.ecosystem == Ecosystem.DEBIAN
        and isinstance(package.ecosystem_data, DpkgDBEntry)
        and package.ecosystem_data
        and package.ecosystem_data.source
    ):
        return (
            package.ecosystem_data.source,
            package.ecosystem_data.source_version or package.version,
        )

    if (
        package.ecosystem == Ecosystem.ALPM
        and isinstance(package.ecosystem_data, AlpmDBEntry)
        and package.ecosystem_data
        and package.ecosystem_data.base_package
    ):
        return package.ecosystem_data.base_package, package.version

    if (
        package.ecosystem == Ecosystem.RPM
        and isinstance(package.ecosystem_data, RpmDBEntry)
        and package.ecosystem_data
        and package.ecosystem_data.source_rpm
    ):
        return _extract_rpm_upstream_info(package.ecosystem_data.source_rpm)

    return None, None


def _extract_rpm_upstream_info(source_rpm: str) -> tuple[str | None, str | None]:
    """Extract upstream package name and version from RPM source package.

    RPM format: NAME-VERSION-RELEASE[.ARCH].src.rpm or NAME-VERSION-RELEASE[.ARCH].nosrc.rpm
    Example: pam-1.5.1-25.el9_6.x86_64.src.rpm -> (pam, 1.5.1-25.el9_6)
    Example: pam-1.5.1-25.el9_6.src.rpm -> (pam, 1.5.1-25.el9_6)
    Example: foo-1-1.el7.nosrc.rpm -> (foo, 1-1.el7.nosrc)
    """
    # Remove source RPM suffixes
    if source_rpm.endswith(".nosrc.rpm"):
        source_rpm = source_rpm[:-10]  # Remove .nosrc.rpm
    elif source_rpm.endswith(".src.rpm"):
        source_rpm = source_rpm[:-8]  # Remove .src.rpm

    # Known RPM architectures - only remove if last component matches these
    known_architectures = {
        "x86_64",
        "i386",
        "i486",
        "i586",
        "i686",
        "aarch64",
        "armv7hl",
        "armv7l",
        "armv6hl",
        "ppc64le",
        "ppc64",
        "s390x",
        "noarch",
    }

    # Remove architecture only if present and recognized
    if "." in source_rpm:
        possible_arch = source_rpm.rsplit(".", 1)[1]
        if possible_arch in known_architectures:
            source_rpm = source_rpm.rsplit(".", 1)[0]

    # Now split by hyphens: NAME-VERSION-RELEASE
    parts = source_rpm.split("-")
    if len(parts) >= 3:
        name = "-".join(parts[:-2])
        version = parts[-2]
        release = parts[-1]
        full_version = f"{version}-{release}"
        return name, full_version

    return None, None


def _get_rhel_distro_info(package: Package) -> tuple[str | None, str | None]:
    """Extract RHEL distribution information from RPM package.

    Returns:
        tuple: (distro_id, distro_version) where:
        - distro_id: "rpm" for RHEL packages
        - distro_version: "rhel9.6" for RHEL 9.6, "rhel8" for RHEL 8, etc.

    """
    if not (
        package.ecosystem == Ecosystem.RPM
        and isinstance(package.ecosystem_data, RpmDBEntry)
        and package.ecosystem_data
        and package.ecosystem_data.release
    ):
        return None, None

    release = package.ecosystem_data.release

    # Look for RHEL pattern: .elX or .elX_Y
    if ".el" not in release:
        return None, None

    # Extract the part after .el (e.g., "9_6" from "63.el9_6")
    el_part = release.split(".el")[-1]
    if not el_part or not el_part[0].isdigit():
        return None, None
    # Parse RHEL version
    if "_" in el_part:
        # Full version: "9_6.1" -> "rhel9.6.1"
        parts = el_part.split("_")
        major, minor = parts[0], parts[1]
        return "rpm", f"rhel{major}.{minor}"

    # Major version only: "9" -> "rhel9"
    return "rpm", f"rhel{el_part}"


def _normalize_rpm_version(version: str) -> str:
    """Normalize RPM version by adding epoch 0: if not present."""
    # Check if version already has an epoch (contains ':')
    if ":" in version:
        return version

    # Add epoch 0: if not present
    return f"0:{version}"


def _get_upstream_info_if_different(
    package: Package, upstream_package: str | None, upstream_version: str | None
) -> tuple[str | None, str | None] | None:
    if (
        upstream_package
        and upstream_version
        and (upstream_package != package.name or upstream_version != package.version)
    ):
        return (upstream_package, upstream_version)
    return None


def update_image_advisories(package: Package) -> list[Advisory]:
    distro_id = None
    distro_version = None
    if package.ecosystem in [Ecosystem.DEBIAN, Ecosystem.ALPM, Ecosystem.ALPINE]:
        distro_id, distro_version, _ = extract_distro_info(package.p_url)
        distro_version = (
            "v" + ".".join(str(distro_version).split(".")[0:2])
            if package.ecosystem == Ecosystem.ALPINE
            else str(distro_version)
        )

    if package.ecosystem == Ecosystem.RPM:
        distro_id, distro_version = _get_rhel_distro_info(package)

    upstream_package, upstream_version = _get_upstream_info(package)
    upstream_info = _get_upstream_info_if_different(package, upstream_package, upstream_version)

    normalized_version = package.version
    if package.ecosystem == Ecosystem.RPM:
        normalized_version = _normalize_rpm_version(package.version)

    return images_advisories.get_vulnerabilities(
        str(distro_id),
        package.name,
        normalized_version,
        distro_version,
        upstream_info,
    )


def get_package_advisories(package: Package) -> list[Advisory] | None:
    try:
        pkg_advisories = []
        if package.ecosystem in ROOT_TYPES:
            pkg_advisories = update_root_advisories(package)
        if package.ecosystem in IMAGES_TYPES:
            pkg_advisories = update_image_advisories(package)
    except ValidationError as ex:
        LOGGER.exception(
            "Unable to complete package advisories",
            extra={
                "extra": {
                    "exception": format_exception(str(ex)),
                    "location": package.locations,
                    "ecosystem": package.ecosystem,
                },
            },
        )
        return None
    return pkg_advisories


def complete_package_advisories(package: Package) -> Package:
    if pkg_advisories := get_package_advisories(package):
        package.advisories = pkg_advisories
    return package
