from pathlib import PurePosixPath

from labels.model.file import Coordinates, Location
from labels.model.package import Language
from labels.model.package_manager import PackageManager
from labels.model.syft_sbom import SyftLocation

# Only patterns produced by syft additional catalogers inside images.
# Directory parsers already set package_manager via get_enriched_location.
_FILENAME_TO_PACKAGE_MANAGER: dict[str, PackageManager] = {
    "Podfile.lock": PackageManager.COCOAPODS,
    "Package.resolved": PackageManager.SWIFT_PM,
    ".package.resolved": PackageManager.SWIFT_PM,
    "pubspec.lock": PackageManager.PUB,
    "pubspec.yaml": PackageManager.PUB,
}


def get_package_manager(file_path: str) -> PackageManager:
    name = PurePosixPath(file_path).name
    return _FILENAME_TO_PACKAGE_MANAGER.get(name, PackageManager.UNKNOWN)


def get_language(language_str: str) -> Language:
    try:
        return Language(language_str.lower())
    except ValueError:
        return Language.UNKNOWN_LANGUAGE


def get_locations(locations: list[SyftLocation]) -> list[Location]:
    return [
        Location(
            access_path=location.access_path,
            package_manager=get_package_manager(location.access_path),
            coordinates=Coordinates(
                real_path=location.access_path,
                file_system_id=location.layer_id,
            ),
        )
        for location in locations
        if (annotation := location.annotations)
        and (evidence := annotation.evidence)
        and evidence == "primary"
    ]
