"""Recreate of the photon (pdg=22) edep histogram in transformed (local-frame)
coordinates, with the deposited-energy axis in electron volts.

Same data path as export_photon_edep.py, but edep is converted from the raw
MeV units to eV (x1e6) so the small-deposition photon spike is readable.
"""

from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

import giant.analysis as a

FILE = "/home/lars/Programming/giant/pbwo4_10k_9_predicted_local.parquet"
OUT = Path("/home/lars/knowledge-base/meta/attachments")

MEV_TO_EV = 1e6

samples = a.load_predicted_local(FILE, sample_frac=0.15)
mask = samples.pdg == 22
edep_idx = a.RAW_TARGET_NAMES.index("edep")
real = samples.real_raw[mask, edep_idx] * MEV_TO_EV  # MeV -> eV
gen = samples.gen_raw[mask, edep_idx] * MEV_TO_EV
print("n photon rows:", mask.sum())
print("real [eV]: mean", real.mean(), "max", real.max(), "frac==0", (real == 0).mean())
print("gen  [eV]: mean", gen.mean(), "max", gen.max(), "frac==0", (gen == 0).mean())

fig, ax = plt.subplots(figsize=(6, 4))
bins = np.linspace(0, np.quantile(real, 0.999), 80)
ax.hist(real, bins=bins, alpha=0.6, label="real", density=True)
ax.hist(gen, bins=bins, alpha=0.6, label="gen", density=True)
ax.set_yscale("log")
ax.set_xlabel("deposited energy [eV] (photons, pdg=22)")
ax.set_ylabel("density")
ax.legend()

fig.tight_layout()
fig.savefig(OUT / "giant-h1024n8d0.1lr3e-4-photon-edep-ev.png", dpi=150, bbox_inches="tight")
print("saved photon-edep-ev")

# Second version: log-spaced energy axis to expose the low-deposition structure.
fig, ax = plt.subplots(figsize=(6, 4))
lo = max(min(real[real > 0].min(), gen[gen > 0].min()), 1.0)
hi = max(real.max(), gen.max())
log_bins = np.geomspace(lo, hi, 80)
ax.hist(real, bins=log_bins, alpha=0.6, label="real", density=True)
ax.hist(gen, bins=log_bins, alpha=0.6, label="gen", density=True)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel("deposited energy [eV] (photons, pdg=22)")
ax.set_ylabel("density")
ax.legend()

fig.tight_layout()
fig.savefig(OUT / "giant-h1024n8d0.1lr3e-4-photon-edep-ev-logx.png", dpi=150, bbox_inches="tight")
print("saved photon-edep-ev-logx")
