# SPDX-FileCopyrightText: 2021-2024 Greenbone AG
#
# SPDX-License-Identifier: AGPL-3.0-or-later

"""
Module for parsing and comparing Gentoo packages (ebuild)

Currently the ebuild are based upon find within `/usr/portage` and are
manipulated as:
sed 's,/usr/portage/([^/]*)/.*/([^/]*).ebuild$,\1/\2,'

Meaning the corresponding name will be:
x11-plugins/wmix-3.5

The version generated by our generator will be delivered via name and version.

The version of the program is program specific hence we could just use Version
of pep440 to guess immediately.
"""

import logging
from dataclasses import dataclass

from .package import Package, PackageComparison

logger = logging.getLogger(__name__)


@dataclass(eq=False)
class EBuildPackage(Package):
    """Represents a .ebuild based package"""

    def compare(self, other: Package) -> PackageComparison:
        if self.name != other.name:
            return PackageComparison.NOT_COMPARABLE

        if self.full_version == other.full_version:
            return PackageComparison.EQUAL

        return self.version_compare(self.full_version, other.full_version)

    @staticmethod
    def from_full_name(full_name: str):
        if not full_name:
            return None
        base_name = (
            full_name[full_name.index("/") + 1 :]
            if "/" in full_name
            else full_name
        )
        if not base_name:
            return None
        d_index = base_name.index("-") if "-" in base_name else len(base_name)
        full_version = base_name[d_index + 1 :]
        if not full_version:
            return None
        return EBuildPackage(
            name=full_name[: len(full_name) - len(base_name[d_index:])],
            full_name=full_name,
            full_version=full_version,
        )

    @staticmethod
    def from_name_and_full_version(name: str, full_version: str):
        if not name or not full_version:
            return None
        name = name.strip()
        full_version = full_version.strip()
        return EBuildPackage(
            name=name,
            full_name=f"{name}-{full_version}",
            full_version=full_version,
        )
