from debputy.manifest_parser.exceptions import ManifestTypeException
from debputy.manifest_parser.parser_data import ParserContextData
from debputy.manifest_parser.util import AttributePath
from debputy.packages import BinaryPackage


def type_mapper_str2package(
    x: str, ap: AttributePath, pc: ParserContextData
) -> BinaryPackage:
    if not pc.is_known_package(x):
        package_names = ", ".join(pc.binary_packages)
        raise ManifestTypeException(
            f'The value "{x}" (from "{ap.path}") does not reference a package declared in'
            f" debian/control. Valid options are: {package_names}"
        )
    package_data = pc.binary_package_data(x)
    if package_data.is_auto_generated_package:
        package_names = ", ".join(pc.binary_packages)
        raise ManifestTypeException(
            f'The package name "{x}" (from "{ap.path}") references an auto-generated package.'
            " However, auto-generated packages are now permitted here. Valid options are:"
            f" {package_names}"
        )
    return package_data.binary_package
