from __future__ import annotations

import shutil
from pathlib import Path

from PIL import Image, ImageStat

import generate_reference_presentation_figures as figures


INPUTS = (
    "m31_cgmsum_henley_shelton2013_absorbed_0p5_2p0.csv",
    "m31_cgmsum_efeds2023_absorbed_0p5_2p0.csv",
    "m31_cgmsum_ueda2022_disk_m31_footprint_absorbed_0p5_2p0.csv",
    "m31_cgmsum_halosat_kaaret2020_disk_adiabatic_halo_m31_extrapolation.csv",
    "m31_cgmsum_v19_primary_measurements_public.csv",
)
STEMS = (
    "henley_population_diagnostic",
    "efeds_scenario_diagnostic",
    "ueda_footprint_diagnostic",
    "halosat_footprint_diagnostic",
)


def test_reference_presentation_figures_rebuild_from_authorities(
    tmp_path: Path, monkeypatch
) -> None:
    for name in INPUTS:
        shutil.copy2(figures.PAPER_DIR / name, tmp_path / name)
    monkeypatch.setattr(figures, "PAPER_DIR", tmp_path)

    figures.main()

    for stem in STEMS:
        for column, width_bounds in (("1col", (900, 1100)), ("2col", (1950, 2200))):
            png = tmp_path / f"{stem}_{column}.png"
            pdf = tmp_path / f"{stem}_{column}.pdf"
            assert png.is_file()
            assert pdf.stat().st_size > 5_000
            with Image.open(png) as image:
                assert width_bounds[0] <= image.width <= width_bounds[1]
                assert image.height > image.width
                variance = ImageStat.Stat(image.convert("L")).var[0]
                assert variance > 100
