"""For every star in the sample: the search on its light curve as observed (the null run), and on
copies with one synthetic self-lensing pulse injected before any preprocessing (the injection
trials). Writes one JSON file per star under the output directory.

    python code/run_trials.py data/sample.json <output dir> [workers]
"""

import hashlib, json, math, os, sys
from multiprocessing import Pool

import numpy as np

sys.path.insert(0, os.path.dirname(__file__))
import selflens as S

TRIALS_PER_STAR = 50
DURATION_RANGE_H = (2.0, 24.0)    # log-uniform
SNR_RANGE = (4.0, 60.0)           # expected white-noise S/N, log-uniform
IMPACT_MAX = 0.9                  # impact parameter, uniform from 0
MIN_GOOD_FRACTION = 0.5           # of a pulse's cadences, else its time is drawn again
SEED = "tess-selflensing-trials-v1"


def rng_for(tic):
    h = hashlib.sha256(f"{SEED}:{tic}".encode()).digest()
    return np.random.default_rng(int.from_bytes(h[:8], "big"))


def clean(x):
    if isinstance(x, float) and not math.isfinite(x):
        return None
    return x


def compact(ev):
    keys = ("time", "snr", "duration_h", "amp", "flare_dchi2", "dist_dump_h", "dist_edge_h",
            "centroid_snr", "background_snr")
    return {k: clean(round(float(ev[k]), 6)) for k in keys}


def draw(lc, prep, rng):
    good = prep["good"]
    t = lc["time"]
    lo, hi = t[good].min(), t[good].max()
    dur = math.exp(rng.uniform(math.log(DURATION_RANGE_H[0]), math.log(DURATION_RANGE_H[1])))
    snr = math.exp(rng.uniform(math.log(SNR_RANGE[0]), math.log(SNR_RANGE[1])))
    b = rng.uniform(0, IMPACT_MAX)
    for _ in range(1000):
        t0 = rng.uniform(lo, hi)
        inside = np.abs(t - t0) < dur / 48.0
        if inside.any() and good[inside].mean() >= MIN_GOOD_FRACTION:
            return t0, dur, b, snr
    raise RuntimeError(f"TIC {lc['tic']}: no time with enough good cadences")


def star(job):
    entry, out_dir = job
    lc = S.load(entry["path"])
    prep, events = S.analyse(lc)
    good = prep["good"]
    record = {
        "tic": lc["tic"], "split": entry["split"], "camera": lc["camera"], "ccd": lc["ccd"],
        "tmag": round(lc["tmag"], 3), "crowdsap": round(lc["crowdsap"], 4),
        "good_cadences": int(good.sum()),
        "span_days": round(float(sum(lc["time"][b] - lc["time"][a] for a, b in prep["spans"])), 4),
        "sigma_ppm": round(float(np.nanmedian(prep["sigma"])) * 1e6, 2),
        "null_events": [compact(e) for e in events],
        "trials": [],
    }
    rng = rng_for(lc["tic"])
    for n in range(TRIALS_PER_STAR):
        t0, dur, b, snr = draw(lc, prep, rng)
        injection, amp = S.injection_for(lc, prep, t0, dur, b, snr)
        window = max(dur / 2.0, 1.0) / 24.0
        _, near = S.analyse(lc, injection, near=(t0, window))
        record["trials"].append({
            "n": n, "t0": round(t0, 6), "duration_h": round(dur, 4), "b": round(b, 4),
            "snr_target": round(snr, 4), "amp": round(float(amp), 8),
            "events": [compact(e) for e in near],
        })
    path = os.path.join(out_dir, f"{lc['tic']}.json")
    with open(path, "w") as f:
        json.dump(record, f, separators=(",", ":"))
    return lc["tic"], len(events)


def main():
    sample_path, out_dir = sys.argv[1], sys.argv[2]
    workers = int(sys.argv[3]) if len(sys.argv) > 3 else min(os.cpu_count() or 1, 8)
    sample = json.load(open(sample_path))
    os.makedirs(out_dir, exist_ok=True)
    root = os.path.dirname(os.path.abspath(sample_path))
    jobs = []
    for entry in sample["stars"]:
        e = dict(entry)
        e["path"] = os.path.join(root, entry["file"]) if not os.path.isabs(entry["file"]) else entry["file"]
        jobs.append((e, out_dir))
    with Pool(workers) as pool:
        for i, (tic, n) in enumerate(pool.imap_unordered(star, jobs), 1):
            if i % 25 == 0 or i == len(jobs):
                print(f"{i}/{len(jobs)} stars done", flush=True)


if __name__ == "__main__":
    main()
