import io
from pathlib import Path

import pytest
from PIL import Image

from modules.core import storage_paths
from tools import resize_images


def _jpg(path, size=(1200, 900), color=(120, 60, 200)):
    path.parent.mkdir(parents=True, exist_ok=True)
    Image.new("RGB", size, color).save(path, format="JPEG")


def _png(path, size=(1200, 900), color=(10, 180, 90)):
    path.parent.mkdir(parents=True, exist_ok=True)
    Image.new("RGBA", size, color + (255,)).save(path, format="PNG")


def _sha(path):
    import hashlib

    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def test_external_data_dir_resolves_to_offers(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))

    assert storage_paths.offers_root_dir() == tmp_path / "offers"


def test_offer_id_scopes_processing_to_one_offer(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    _jpg(tmp_path / "offers" / "101" / "image_101_url_0.jpg", size=(4000, 3000))
    _jpg(tmp_path / "offers" / "202" / "image_202_url_0.jpg", size=(4000, 3000))

    resize_images.run(offer_id="101")

    with Image.open(tmp_path / "offers" / "101" / "image_101_url_0.jpg") as img:
        assert img.size == (2000, 1500)
    with Image.open(tmp_path / "offers" / "202" / "image_202_url_0.jpg") as img:
        assert img.size == (4000, 3000)


@pytest.mark.parametrize("value", ["../101", "101/202", "abc", "", "10.."])
def test_invalid_offer_id_is_rejected(value):
    with pytest.raises(argparse_error()):
        resize_images.parse_args(["--offer-id", value])


def argparse_error():
    return SystemExit


def test_dry_run_performs_no_filesystem_mutations(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    image_path = tmp_path / "offers" / "101" / "image_101_url_0.jpg"
    png_path = tmp_path / "offers" / "101" / "image_101_url_1.png"
    _jpg(image_path, size=(4000, 3000))
    _png(png_path)
    before = {path: _sha(path) for path in (image_path, png_path)}

    stats = resize_images.run(offer_id="101", dry_run=True)

    assert stats["conversions"] == 0
    assert stats["conversion_skips"] == 1
    assert stats["resizes"] == 1
    assert stats["thumbnails"] == 1
    assert {path: _sha(path) for path in (image_path, png_path)} == before
    assert not (tmp_path / "offers" / "101" / "thumbnail.jpg").exists()
    assert not (tmp_path / "offers" / "101" / "image_101_url_1.jpg").exists()
    assert not (tmp_path / "databases").exists()  # dry-run creates no lock/history


def test_conversion_retains_original_without_creating_alias(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    source = tmp_path / "offers" / "101" / "image_101_url_1.png"
    target = tmp_path / "offers" / "101" / "image_101_url_1.jpg"
    _png(source)

    resize_images.run(offer_id="101")

    assert source.is_file()
    assert not target.exists()


def test_already_small_jpg_is_not_rewritten(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    image_path = tmp_path / "offers" / "101" / "image_101_url_1.jpg"
    _jpg(image_path, size=(1200, 900))
    before = _sha(image_path)

    resize_images.resize_large_images([image_path.parent])

    assert _sha(image_path) == before


def test_second_run_does_not_resize_already_compliant_image_again(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    image_path = tmp_path / "offers" / "101" / "image_101_url_0.jpg"
    _jpg(image_path, size=(4000, 3000))

    resize_images.run(offer_id="101")
    with Image.open(image_path) as img:
        assert img.size == (2000, 1500)

    resize_images.run(offer_id="101")
    with Image.open(image_path) as img:
        assert img.size == (2000, 1500)


def test_thumbnail_is_created_from_main_image(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    _jpg(tmp_path / "offers" / "101" / "image_101_url_0.jpg")

    resize_images.run(offer_id="101")

    with Image.open(tmp_path / "offers" / "101" / "thumbnail.jpg") as img:
        assert img.size == (400, 300)


def test_exif_orientation_is_applied_for_resize(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    image_path = tmp_path / "image.jpg"
    image = Image.new("RGB", (4000, 2000), (200, 20, 20))
    exif = Image.Exif()
    exif[274] = 6
    image.save(image_path, format="JPEG", exif=exif)

    resize_images.resize_large_images([tmp_path])

    with Image.open(image_path) as img:
        assert img.size == (1000, 2000)


@pytest.mark.parametrize("extension", [".JPG", ".JPEG", ".jpg", ".jpeg", ".JpEg", ".PNG"])
def test_thumbnail_reads_original_extension_without_renaming(tmp_path, monkeypatch, extension):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    folder = tmp_path / "offers" / "101"
    source = folder / f"image_101_url_0{extension}"
    (_png if extension == ".PNG" else _jpg)(source)
    before = (source.name, _sha(source), source.stat().st_mtime_ns)

    stats = resize_images.create_or_update_thumbnails([folder])

    assert stats["errors"] == stats["missing_thumbnail_sources"] == 0
    assert (source.name, _sha(source), source.stat().st_mtime_ns) == before
    assert {p.name for p in folder.iterdir()} == {source.name, "thumbnail.jpg"}
    with Image.open(folder / "thumbnail.jpg") as img:
        assert img.format == "JPEG" and img.size == (400, 300)


def test_thumbnail_ambiguous_fallback_keeps_existing_files(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    folder = tmp_path / "offers" / "101"
    _jpg(folder / "image_101_url_0.JPEG")
    _png(folder / "image_101_url_0.png")
    _jpg(folder / "thumbnail.jpg", size=(40, 30))
    before = {p.name: _sha(p) for p in folder.iterdir()}

    stats = resize_images.create_or_update_thumbnails([folder])

    assert stats["errors"] == 1 and stats["thumbnails"] == 0
    assert {p.name: _sha(p) for p in folder.iterdir()} == before


def test_thumbnail_rejects_canonical_jpg_with_duplicate_other_format(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    folder = tmp_path / "offers" / "101"
    canonical = folder / "image_101_url_0.jpg"
    _jpg(canonical)
    _png(folder / "image_101_url_0.png")

    with pytest.raises(ValueError, match="Ambiguous"):
        resize_images._thumbnail_source(folder)


@pytest.mark.parametrize("extension", [".JPG", ".JpG"])
def test_thumbnail_selection_with_case_sensitive_lookup(tmp_path, monkeypatch, extension):
    folder = tmp_path / "101"
    source = folder / f"image_101_url_0{extension}"
    _jpg(source)
    canonical = str(folder / "image_101_url_0.jpg")
    original_is_file = Path.is_file
    # Windows would otherwise resolve .jpg to .JPG and never exercise fallback.
    with monkeypatch.context() as patch:
        patch.setattr(Path, "is_file", lambda path: False if str(path) == canonical else original_is_file(path))
        selected = resize_images._thumbnail_source(folder)
    assert str(selected) == str(source)


def test_thumbnail_uppercase_dry_run_has_no_writes(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    source = tmp_path / "offers" / "101" / "image_101_url_0.JPG"
    _jpg(source)
    before = (_sha(source), source.stat().st_mtime_ns)

    stats = resize_images.create_or_update_thumbnails([source.parent], dry_run=True)

    assert stats["thumbnails"] == 1 and stats["errors"] == 0
    assert (_sha(source), source.stat().st_mtime_ns) == before
    assert list(source.parent.iterdir()) == [source]
    assert not (tmp_path / "databases").exists()


def test_corrupt_thumbnail_source_does_not_stop_other_offers(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    bad = tmp_path / "offers" / "101"
    bad.mkdir(parents=True)
    (bad / "image_101_url_0.JPG").write_bytes(b"synthetic invalid JPEG")
    good = tmp_path / "offers" / "202"
    _jpg(good / "image_202_url_0.JPEG")

    stats = resize_images.create_or_update_thumbnails([bad, good])

    assert stats["errors"] == 1
    assert not (bad / "thumbnail.jpg").exists()
    assert (good / "thumbnail.jpg").is_file()
    assert (bad / "image_101_url_0.JPG").read_bytes() == b"synthetic invalid JPEG"




def test_conversion_collision_preserves_both_files(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    folder = tmp_path / "offers" / "101"
    _jpg(folder / "image_101_url_0.jpg")
    _png(folder / "image_101_url_0.png")
    before = {p.name: _sha(p) for p in folder.iterdir()}

    stats = resize_images.normalize_extensions([folder])

    assert stats["errors"] == 1
    assert {p.name: _sha(p) for p in folder.iterdir()} == before


def test_extremely_large_image_requires_multiple_runs(tmp_path, monkeypatch):
    # Characterize the existing halve-once policy with a scaled-down threshold.
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    source = tmp_path / "offers" / "101" / "image_101_url_0.JPG"
    _jpg(source, size=(120, 60))
    resize_images.resize_large_images([source.parent], min_dimension=29)
    with Image.open(source) as img:
        assert img.size == (60, 30)
    resize_images.resize_large_images([source.parent], min_dimension=29)
    with Image.open(source) as img:
        assert img.size == (30, 15)


def test_cron_second_run_does_not_write_thumbnail(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    source = tmp_path / "offers/101/image_101_url_0.JPG"
    _jpg(source)
    first = resize_images.run(offer_id="101")
    thumbnail = source.parent / "thumbnail.jpg"
    before = (_sha(thumbnail), thumbnail.stat().st_mtime_ns)
    second = resize_images.run(offer_id="101")
    assert first["thumbnails"] == 1
    assert second["thumbnails"] == 0 and second["thumbnail_skips"] == 1
    assert (_sha(thumbnail), thumbnail.stat().st_mtime_ns) == before


def test_source_bytes_change_even_with_same_mtime_regenerates(tmp_path, monkeypatch):
    import os
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    source = tmp_path / "offers/101/image_101_url_0.JPEG"
    _jpg(source)
    resize_images.run(offer_id="101")
    before = _sha(source.parent / "thumbnail.jpg")
    timestamp = source.stat().st_mtime_ns
    _jpg(source, color=(1, 2, 3))
    os.utime(source, ns=(timestamp, timestamp))
    assert resize_images.run(offer_id="101")["thumbnails"] == 1
    assert _sha(source.parent / "thumbnail.jpg") != before


@pytest.mark.parametrize("parameter,value", [
    ("THUMBNAIL_SIZE", (200, 150)), ("THUMBNAIL_QUALITY", 90),
    ("THUMBNAIL_RECIPE_VERSION", 2), ("PILLOW_VERSION", "synthetic-next-version"),
])
def test_generation_parameter_change_regenerates(tmp_path, monkeypatch, parameter, value):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    source = tmp_path / "offers/101/image_101_url_0.jpg"
    _jpg(source)
    resize_images.run(offer_id="101")
    monkeypatch.setattr(resize_images, parameter, value)
    assert resize_images.run(offer_id="101")["thumbnails"] == 1
    assert resize_images.run(offer_id="101")["thumbnail_skips"] == 1


def test_offer_without_photos_is_normal_and_quiet(tmp_path, monkeypatch, capsys):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    folder = tmp_path / "offers/612"
    folder.mkdir(parents=True)
    stats = resize_images.run(offer_id="612")
    assert stats["errors"] == stats["thumbnails"] == 0
    assert stats["missing_thumbnail_sources"] == 1
    assert "No source image" not in capsys.readouterr().out
    assert not list(folder.iterdir())


def test_bad_thumbnail_is_regenerated(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    source = tmp_path / "offers/101/image_101_url_0.jpg"
    _jpg(source)
    resize_images.run(offer_id="101")
    (source.parent / "thumbnail.jpg").write_bytes(b"corrupt synthetic output")
    assert resize_images.run(offer_id="101")["thumbnails"] == 1


def test_collision_prevents_resize_and_preserves_all_sources(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    folder = tmp_path / "offers/101"
    _jpg(folder / "image_101_url_0.jpg", size=(3000, 10))
    _jpg(folder / "image_101_url_0.JPEG", size=(3000, 10))
    before = {p.name: _sha(p) for p in folder.iterdir()}
    assert resize_images.main(["--offer-id", "101"]) == 1
    assert {p.name: _sha(p) for p in folder.iterdir()} == before



def test_synthetic_hosting_counts_221_offers_220_current_thumbnails(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    for identifier in range(1000, 1220):
        _jpg(tmp_path / f"offers/{identifier}/image_{identifier}_url_0.JPG", size=(8, 8))
    (tmp_path / "offers/612").mkdir()
    first = resize_images.run()
    before = {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in (tmp_path / "offers").glob("*/thumbnail.jpg")}
    second = resize_images.run()
    assert first["offers_scanned"] == second["offers_scanned"] == 221
    assert first["thumbnails"] == 220
    assert second["thumbnails"] == 0 and second["thumbnail_skips"] == 220
    assert second["missing_thumbnail_sources"] == 1 and second["errors"] == 0
    assert {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in before} == before


def test_failed_atomic_resize_keeps_original(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    source = tmp_path / "offers/101/image_101_url_0.JPG"
    _jpg(source, size=(3000, 10))
    before = source.read_bytes()
    def fail(*args, **kwargs):
        raise OSError("synthetic save failure")
    monkeypatch.setattr(Image.Image, "save", fail)
    stats = resize_images.resize_large_images([source.parent])
    assert stats["errors"] == 1
    assert source.read_bytes() == before
    assert not list(source.parent.glob("*.tmp"))
