"""One ordered selection for counting and reading domestic offer photos.

ZIP/XML positions are dense; source indexes may have gaps. No source is renamed.
"""
import re


class GalleryError(ValueError):
    pass


def image_index(filename, offer_id):
    match = re.fullmatch(r"image_" + re.escape(str(offer_id)) + r"_url_([0-9]+)\.(?:jpe?g|png)", str(filename), re.IGNORECASE)
    return int(match[1]) if match else None


def resolve_gallery(filenames, offer_id):
    by_index = {}
    for name in filenames:
        name = str(name)
        index = image_index(name, offer_id)
        if index is None:
            continue
        if index in by_index:
            raise GalleryError(f"Ambiguous photo index {index} for offer {offer_id}")
        by_index[index] = name
    return tuple(by_index[index] for index in sorted(by_index))


class PhotoCount(int):
    """An integer for unchanged renderers, carrying the exact selected sources.

    This is an internal gateway/packager value, never part of a manifest or RPC.
    """
    def __new__(cls, names, source):
        value = super().__new__(cls, len(names))
        value.names = tuple(names)
        value.source = source
        return value

    def __reduce__(self):
        return type(self), (self.names, self.source)
