"""Simulated data sets for the Lecture 9 hands-on (same as the slides)."""
import numpy as np


def make_xray_file(path="sim_smc_pulsar_pn.fits", seed=2026):
    """XMM/EPIC-pn-like event file of an SMC pulsar (P = 11.877 s, 11% pulsed, double-peaked),
    with a soft-proton flare and a data drop excluded by the GTIs. PI in eV."""
    from astropy.io import fits
    rng = np.random.default_rng(seed)
    P_TRUE, T_OBS, MET0 = 11.877, 40000.0, 7.5e8
    r_src, r_bkg, pf = 0.30, 0.06, 0.11
    def profile(ph):
        return 0.02 + 0.9 * np.exp(-0.5 * ((ph - 0.25) / 0.07)**2) + 0.45 * np.exp(-0.5 * ((ph - 0.68) / 0.09)**2)
    ph_ = np.linspace(0, 1, 2001); pmean = profile(ph_).mean(); pmax = profile(ph_).max()
    lam_max = r_src * ((1 - pf) + pf * pmax / pmean)
    n = rng.poisson(lam_max * T_OBS); ts = np.sort(rng.uniform(0, T_OBS, n))
    ts = ts[rng.uniform(0, lam_max, n) < r_src * ((1 - pf) + pf * profile((ts / P_TRUE) % 1) / pmean)]
    tb = np.sort(rng.uniform(0, T_OBS, rng.poisson(r_bkg * T_OBS)))
    tfl = np.sort(rng.uniform(14000, 19000, rng.poisson(1.5 * 5000)))
    t_all = np.concatenate([ts, tb, tfl])
    src = np.concatenate([np.ones(ts.size, bool), np.zeros(tb.size + tfl.size, bool)])
    drop = (t_all > 30000) & (t_all < 31500)
    t_all, src = t_all[~drop], src[~drop]
    E = np.empty(t_all.size)
    E[src] = np.clip(rng.gamma(2.0, 2500.0, src.sum()) + 300, 200, 12000)
    E[~src] = np.clip(rng.exponential(1800.0, (~src).sum()) + 200, 200, 15000)
    o = np.argsort(t_all); t_all, E = t_all[o], E[o]
    gti = np.array([[0.0, 14000.0], [19000.0, 30000.0], [31500.0, T_OBS]]) + MET0
    ev = fits.BinTableHDU.from_columns([fits.Column(name="TIME", format="D", array=t_all + MET0, unit="s"),
                                        fits.Column(name="PI", format="J", array=np.round(E).astype(int), unit="eV")],
                                       name="EVENTS")
    for k, v in dict(TELESCOP="XMM", INSTRUME="EPN", MJDREF=50814.0, TIMEZERO=0.0, TIMESYS="TT",
                     TSTART=MET0, TSTOP=MET0 + T_OBS, EXPOSURE=float(np.sum(gti[:, 1] - gti[:, 0])),
                     OBJECT="SIM SMC PULSAR").items():
        ev.header[k] = v
    g = fits.BinTableHDU.from_columns([fits.Column(name="START", format="D", array=gti[:, 0]),
                                       fits.Column(name="STOP", format="D", array=gti[:, 1])], name="STDGTI")
    fits.HDUList([fits.PrimaryHDU(), ev, g]).writeto(path, overwrite=True)
    return path


def ogle_cadences(seed=31):
    """Observation times for two OGLE-like cadences: sparse (3 seasons, 1 point / 1-3 nights)
    and dense (60 nights, 5-7 points per night)."""
    rng = np.random.default_rng(seed)
    tA = []
    for s0 in (0, 365, 730):
        d = s0
        while d < s0 + 230:
            if rng.random() < 0.8:
                tA.append(d + 0.15 + 0.0012 * (d - s0) + rng.normal(0, 0.02))
            d += rng.integers(1, 4)
    tB = []
    for n_ in range(60):
        if rng.random() < 0.85:
            tB.extend(n_ + 0.05 + np.sort(rng.uniform(0, 0.25, rng.integers(5, 8))))
    return np.array(tA), np.array(tB)


def be_star(t, f1=1.55, a1=0.012):
    """SMC Be star: non-radial pulsation + slow variation (I mag)."""
    return 15.5 + a1 * np.sin(2 * np.pi * f1 * t + 0.3) + 0.004 * np.sin(2 * np.pi * t / 60.0)


def eclipsing(t, P=1.2345):
    ph = (t / P) % 1
    d1 = 0.30 * np.exp(-0.5 * (np.minimum(ph, 1 - ph) / 0.035)**2)
    d2 = 0.12 * np.exp(-0.5 * ((ph - 0.5) / 0.035)**2)
    return 16.2 + d1 + d2 - 0.02 * np.cos(4 * np.pi * ph)


def monday_hook():
    """The three light curves of Lecture 8, slide 2 (amplitudes 1, 0.3, 0.1; P = 7.7; sigma = 0.4)."""
    rng = np.random.default_rng(22)
    t = np.linspace(0, 100, 101)
    return t, [1 + A * np.sin(2 * np.pi * t / 7.7 + 0.4) + rng.normal(0, 0.4, t.size) for A in (1.0, 0.3, 0.1)]
