# %% [markdown]
# # Test the fitted burst against the quiet camera record
#
# A slowly falling crystal can reach the camera later than a broken pellet
# from the same refreezing layer. A fit can use that delay to match the crest.
# The following 45 minutes test where its delayed crystals went. Use the
# complete example download to compare the two predictions with the camera
# using only the published five-minute plot values.

# %%
import csv
from io import TextIOWrapper
from pathlib import Path
from statistics import mean
from zipfile import ZipFile


def plot_archive():
    """Find the six-table plot archive in the checkout or downloaded bundle."""
    here = Path(globals().get("__file__", ".")).resolve().parent
    for start in (Path.cwd(), here):
        for folder in (start, *start.parents):
            for path in (
                folder / "plot-data.zip",
                folder
                / "website/public/study-data/hyytiala-ice-burst/plot-data.zip",
            ):
                if path.is_file():
                    return path
    raise FileNotFoundError(
        "Extract the complete example ZIP with plot-data.zip."
    )


# %% [markdown]
# The camera column contains flux derived from measured sizes, fall speeds
# and number densities. The other columns contain fitted ground flux from
# the same inferred breakup supply. One fit keeps a common yield and varies
# flight times. The other varies the yield of visible arrivals. Exclude every
# five-minute interval used to fit either model by starting at 17:10 UTC.

# %%
with ZipFile(plot_archive()) as archive:
    with archive.open("ground-flux.csv") as binary:
        flux = list(csv.DictReader(TextIOWrapper(binary, encoding="utf-8")))

quiet = [row for row in flux if 1030 <= int(row["start_utc_min"]) < 1075]
assert [int(row["start_utc_min"]) for row in quiet] == list(
    range(1030, 1075, 5)
)
for name, key in (
    ("Camera-derived flux", "measured"),
    ("Constant yield, variable travel time", "constant_yield"),
    ("Variable visible supply", "variable_supply"),
):
    average = mean(float(row[key]) for row in quiet)
    print(f"{name}: {average:.2f} crystals m⁻² s⁻¹")

# %% [markdown]
# The camera recorded 5.54 crystals m⁻² s⁻¹. The timing-only fit predicts
# hundreds of late arrivals. A changing supply can account for the quieter
# tail, but the earlier camera and radar observations still allow either
# more fragments per breakup or an ice-rich region moving over the site.
