"""Real source names -> dense JPEG ZIP entries, without changing originals."""
import io
import copy
import zipfile

import pytest
from PIL import Image

from InvestmentManager.export_engine import export_packaging as packaging
from InvestmentManager.export_engine.gallery import GalleryError, PhotoCount, resolve_gallery


@pytest.fixture()
def gallery(tmp_path, monkeypatch):
    folder = tmp_path / "17"
    folder.mkdir()
    monkeypatch.setattr(packaging.runtime_paths, "local_offer_dir", lambda offer: folder)
    # Local reader remains isolated and is separately exercised by real generator tests.
    monkeypatch.setattr(packaging, "read_file_bytes", lambda path: path.read_bytes())
    monkeypatch.setattr(packaging.runtime_paths, "checked_path", lambda path: path)
    monkeypatch.setattr(packaging, "_get_logo_bytes", lambda offer: None)
    monkeypatch.setattr(packaging, "_get_agent_photo_bytes", lambda agent: None)
    packaging._ASSET_CACHE["offers"].clear()
    def photo(index, extension, color):
        path = folder / f"image_17_url_{index}{extension}"
        Image.new("RGB", (32, 24), color).save(path, format="JPEG")
        return path
    return folder, photo


@pytest.mark.parametrize("extension", [".jpg", ".JPG", ".jpeg", ".JPEG"])
@pytest.mark.parametrize("packager", ["package_files", "package_files_od", "package_files_dp", "package_files_to", "package_files_gruntguru"])
def test_gaps_and_extensions_keep_pixels_and_dense_zip_names(gallery, extension, packager):
    folder, photo = gallery
    sources = [photo(2, extension, (120, 30, 10)), photo(9, ".JPEG", (10, 100, 30))]
    before = {p.name: p.read_bytes() for p in sources}
    selection = packaging.count_photos(17)
    assert selection == 2
    assert selection.names == tuple(p.name for p in sources)
    assert copy.deepcopy(selection).names == selection.names
    _, body = getattr(packaging, packager)(17, selection, "<synthetic/>", "Dodaj", 7)
    with zipfile.ZipFile(io.BytesIO(body)) as archive:
        images = sorted(n for n in archive.namelist() if n.endswith(".jpg"))
        assert images == ["image_17_url_0.jpg", "image_17_url_1.jpg"]
        for name, source in zip(images, sources):
            assert archive.read(name) == before[source.name]
            with Image.open(io.BytesIO(archive.read(name))) as img:
                assert img.format == "JPEG"
    assert {p.name: p.read_bytes() for p in sources} == before


@pytest.mark.parametrize("names", [
    ["image_17_url_0.jpg", "image_17_url_0.JPG"],
    ["image_17_url_0.jpg", "image_17_url_0.jpeg"],
    ["image_17_url_01.JPG", "image_17_url_1.JPEG"],
])
def test_ambiguous_index_is_rejected_on_any_filesystem(names):
    with pytest.raises(GalleryError, match="Ambiguous photo index"):
        resolve_gallery(names, 17)


def test_empty_gallery(gallery):
    assert packaging.count_photos(17) == 0
    assert packaging._get_offer_images(17, packaging.count_photos(17)) == {}


def test_new_export_does_not_reuse_old_photo_bytes(gallery):
    folder, photo = gallery
    source = photo(0, ".JPEG", (1, 2, 3))
    first = packaging._get_offer_images(17, packaging.count_photos(17))
    photo(0, ".JPEG", (200, 30, 60))
    second = packaging._get_offer_images(17, packaging.count_photos(17))
    assert first[0] != second[0] == source.read_bytes()


def test_changed_selection_is_rejected_before_read(gallery):
    folder, photo = gallery
    photo(0, ".jpg", (1, 2, 3))
    selection = packaging.count_photos(17)
    photo(9, ".JPEG", (4, 5, 6))
    with pytest.raises(GalleryError, match="selection changed"):
        packaging._get_offer_images(17, selection)



def test_png_is_converted_only_inside_zip_without_creating_disk_alias(gallery):
    folder, photo = gallery
    source = folder / "image_17_url_7.PNG"
    Image.new("RGBA", (32, 24), (10, 200, 40, 255)).save(source, format="PNG")
    before = source.read_bytes()
    selection = packaging.count_photos(17)
    assert selection.names == (source.name,)
    _, body = packaging.package_files(17, selection, "<synthetic/>", "Dodaj", 7)
    with zipfile.ZipFile(io.BytesIO(body)) as archive:
        with Image.open(io.BytesIO(archive.read("image_17_url_0.jpg"))) as image:
            assert image.format == "JPEG" and image.size == (32, 24)
    assert source.read_bytes() == before
    assert {p.name for p in folder.iterdir()} == {source.name}
