"""Data, prayer clock and rehearsal holes for the crowd-monitoring tutorial.

The data are the two CSV files of the Kaggle competition (train.csv, test.csv).
Put them in ./data, or point the environment variable CROWD_DATA to their folder.
"""
import os

import numpy as np
import pandas as pd

DATA = os.environ.get("CROWD_DATA", os.path.join(os.path.dirname(os.path.abspath(__file__)), "data"))
THREADS = os.environ.get("THREADS", "4:1")              # threads for pyINLA: 4 for the model, 1 for the linear algebra
PLAZA = ["cam_A", "cam_E", "cam_F"]                      # the three largest cameras, which move together
KINDS = ["forecast", "hidden", "hidden-future", "missing"]
# Rehearsal: a training day receives the hole pattern of the test day one week later.
REHEARSAL = {"20260911_1100": "20260918_1100", "20260912_1100": "20260919_1100"}
# The later day is blank for 30 minutes after each of its cutoffs. The rehearsal cutoffs and gaps are placed
# 30 minutes later, so that the minutes to forecast are minutes that the later day shows.
SHIFT = 30
DAYNAME = {"2026-09-11": "Fri 11 Sep", "2026-09-12": "Sat 12 Sep"}


def codes(*columns):
    """Number the distinct values (or combinations of values) 1, 2, ... in sorted order: an index for a model term."""
    return pd.factorize(pd.Series(list(zip(*columns))), sort=True)[0] + 1


def pc(u):
    """Prior for the standard deviation of a term: P(sd > u) = 0.01. A penalised-complexity prior."""
    return {"prec": {"prior": "pc.prec", "param": [u, 0.01]}}


def ar1(u):
    """AR(1) across the groups of a term, with a prior for its correlation: P(rho > u) = 0.5."""
    return {"model": "ar1", "hyper": {"rho": {"prior": "pc.cor1", "param": [u, 0.5]}}}


def prayer_times(day, lat=24.4672, lon=39.6111, tz=3.0, fajr_angle=18.5, isha_after=90):
    """Adhan times in Madinah (Umm al-Qura convention) from the sun's position, in minutes after local midnight."""
    rad = np.pi / 180
    n = pd.Timestamp(day).to_julian_date() + 0.5 - tz / 24 - 2451545          # days since J2000 at local noon
    g = ((357.529 + 0.98560028 * n) % 360) * rad
    q = (280.459 + 0.98564736 * n) % 360
    L = ((q + 1.915 * np.sin(g) + 0.020 * np.sin(2 * g)) % 360) * rad
    e = (23.439 - 0.00000036 * n) * rad
    ra = np.arctan2(np.cos(e) * np.sin(L), np.cos(L)) / rad / 15
    decl = np.arcsin(np.sin(e) * np.sin(L))
    noon = 12 + tz - lon / 15 - (((q / 15 - ra % 24) + 12) % 24 - 12)

    def hour_angle(alt):
        c = (np.sin(alt * rad) - np.sin(lat * rad) * np.sin(decl)) / (np.cos(lat * rad) * np.cos(decl))
        return np.arccos(np.clip(c, -1, 1)) / rad / 15

    asr_alt = np.arctan(1 / (1 + np.tan(abs(lat * rad - decl)))) / rad
    t = {"fajr": noon - hour_angle(-fajr_angle), "dhuhr": noon + 1 / 60, "asr": noon + hour_angle(asr_alt),
         "maghrib": noon + hour_angle(-0.833)}
    t = {k: 60 * v for k, v in t.items()}
    t["isha"] = t["maghrib"] + isha_after
    return t


def prayer_clock(day, minute, ref_day="2026-09-11"):
    """Minute of day on the prayer clock: the day is stretched so that its adhans fall where those of
    ref_day do."""
    a, r = prayer_times(day), prayer_times(ref_day)
    return np.interp(minute, [0, *a.values(), 1440], [0, *r.values(), 1440])


def load():
    """All rows of the table. `people` is NaN on the holes of the two test days."""
    tr = pd.read_csv(os.path.join(DATA, "train.csv"))
    te = pd.read_csv(os.path.join(DATA, "test.csv"))
    d = pd.concat([tr, te], ignore_index=True)
    d["recording"] = d["recording"].astype(str)
    d["now"] = d.pop("now_minute_of_day")
    return d[["id", "recording", "day", "weekday", "unit", "minute_of_day", "people", "kind", "now", "horizon"]]


def rehearsal(d):
    """Copy each test day's holes onto the same weekday one week earlier, where the truth is known.

    Every cutoff and gap keeps its distance from the nearest adhan and is then moved SHIFT minutes later.
    Adds three columns:
      obs    True where the model may use the value (released and not a rehearsal hole)
      role   kind of rehearsal hole ('' elsewhere)
      rnow   cutoff of a forecast / hidden-future rehearsal hole
    """
    d = d.copy()
    released = d.people.notna().to_numpy()
    obs, role, rnow = released.copy(), np.full(len(d), "", dtype=object), np.full(len(d), np.nan)
    minute, unit = d.minute_of_day.to_numpy(), d.unit.to_numpy()
    day_of = d.groupby("recording").day.first()

    def move(t, src, val):
        ps, pv = np.array(list(prayer_times(day_of[src]).values())), np.array(list(prayer_times(day_of[val]).values()))
        k = np.abs(np.asarray(t, float)[:, None] - ps[None, :]).argmin(1)
        return np.round(t + pv[k] - ps[k]).astype(int)

    plan = {}
    for val, src in REHEARSAL.items():
        r = (d.recording == val).to_numpy()
        s = d[d.recording == src]
        hid = sorted(s[s.kind == "hidden"].unit.unique())
        nows = np.sort(move(s[s.kind == "forecast"].now.dropna().unique(), src, val)) + SHIFT
        nows = nows[(nows >= 660) & (nows + 15 <= 1274)]
        plan[val] = dict(hidden=hid, nows=nows)
        h = r & np.isin(unit, hid)                                     # hidden cameras: the whole day
        obs[h] = False; role[h & released] = "hidden"
        g = s[(s.kind == "missing") & ~s.unit.isin(hid)]               # short gaps
        gaps = set(zip(g.unit, move(g.minute_of_day.to_numpy(), src, val) + SHIFT))
        g = r & np.array([(u, m) in gaps for u, m in zip(unit, minute)])
        obs[g] = False; role[g & released] = "missing"
        for n in nows:                                                 # cutoffs: 30 blank minutes, the first 15 held out
            blank = r & (minute > n) & (minute <= n + 30)
            obs[blank] = False
            held = blank & (minute <= n + 15) & released
            role[blank & ~held] = ""
            role[held] = np.where(np.isin(unit[held], hid), "hidden-future", "forecast")
            rnow[held] = n
    d["obs"], d["role"], d["rnow"] = obs, role, rnow
    return d, plan


def holes(d):
    """The rehearsal holes: truth y, kind and cutoff."""
    v = d[d.role != ""]
    return pd.DataFrame({"recording": v.recording, "day": v.day, "unit": v.unit, "minute_of_day": v.minute_of_day,
                         "kind": v.role, "now": v.rnow, "y": v.people}, index=v.index)


if __name__ == "__main__":
    d, plan = rehearsal(load())
    for rec, p in plan.items():
        print(rec, "hidden:", p["hidden"], "cutoffs:", list(p["nows"]))
    print(holes(d).groupby(["day", "kind"]).size().unstack())
