#!/usr/bin/env python3
"""Turn the saved boot journal into a small, deterministic instrumental score.

Nothing talks to systemd, the network, or the speakers. The clock below is an
artistic mapping of journal reception times, not a hardware model. Requires
numpy and scipy; `python3 synth.py` writes audio + an explicit event score.
"""
from __future__ import annotations

import hashlib
import json
import math
from pathlib import Path

import numpy as np
from scipy.io import wavfile
from scipy.signal import butter, sosfilt

HERE = Path(__file__).resolve().parent
FS = 32000
PENT = [0, 3, 5, 7, 10]


def seed(text: str) -> int:
    return int.from_bytes(hashlib.sha256(text.encode()).digest()[:8], "big")


def family(unit: str) -> str:
    if unit.endswith(".timer"):
        return "clocks"
    if unit == "systemd-timedated.service":
        return "timekeeper"
    if "gpu-sentinel" in unit:
        return "sentinel"
    if "attic-index" in unit:
        return "attic"
    if "raccoon-backup" in unit:
        return "drayage"
    if "house-atlas-build" in unit:
        return "cartographer"
    if any(s in unit for s in ("hot-goss", "collider-refresh")):
        return "whispers"
    if "night-kitchen" in unit:
        return "kitchen"
    if any(s in unit for s in ("network", "resolved", "ssh", "postfix", "dbus", "burrow", "basin", "house-atlas", "barnacle-oracle")):
        return "door"
    return "floorboards"


def mapped_time(seconds: float, end: float, cfg: dict) -> float:
    # Sparkle-Bird's three speeds: make room for the first four seconds rather
    # than turning the whole boot cluster into a single digital click.
    return cfg["lead_in_s"] + float(np.interp(seconds, [0, 15, 360, end], [0, 13.5, 32, cfg["score_s"]]))


def make_score(source: dict, cfg: dict) -> list[dict]:
    events = source["events"]
    end = max(e["offset_s"] for e in events)
    out, last_timeout = [], {}
    for event in events:
        e = dict(event)
        h = seed(e["unit"])
        fam = family(e["unit"])
        midi = cfg["voices"][fam]["midi"] + PENT[h % 5] + (12 if (h // 5) % 2 else 0)
        e.update(family=fam, midi=midi, hz=round(440 * 2 ** ((midi - 69) / 12), 5),
                 at_s=round(mapped_time(e["offset_s"], end, cfg), 6),
                 pan=round(((h // 10) % 1001) / 1000 * 1.3 - .65, 4), audible=True)
        if e["verb"] == "Timed out":
            last_timeout[e["unit"]] = e
        if e["verb"] == "Failed to start" and e["unit"] in last_timeout:
            prior = last_timeout[e["unit"]]
            if e["offset_s"] - prior["offset_s"] < .2:
                e.update(audible=False, folded_into=prior["id"],
                         note="One timeout termination, two journal notices; one bent note.")
        out.append(e)
    timers = [e for e in out if e["family"] == "clocks"]
    for i, e in enumerate(timers):
        e["journal_mapped_at_s"] = e["at_s"]
        e["at_s"] = round(e["at_s"] + cfg["timer_fan_s"] * i / max(1, len(timers) - 1), 6)
        e["hz"] = round(1100 * 2 ** (1.5 * i / max(1, len(timers) - 1)), 5)
        e["pan"] = round(-.8 + 1.6 * i / max(1, len(timers) - 1), 4)
        e["note"] = "Deliberate 1.2-second musical fan-out; not a measured startup delay."
    for e in out:
        # Simultaneous timer notices remain simultaneous, but not 24x louder.
        count = sum(x["audible"] and abs(x["at_s"] - e["at_s"]) < .035 for x in out)
        e["density_gain"] = round(1 / math.sqrt(max(1, count)), 6)
    return out


def instrument(e: dict, cfg: dict) -> np.ndarray:
    f, fam, verb = e["hz"], e["family"], e["verb"]
    failure = verb in ("Timed out", "Failed to start")
    durations = dict(clocks=.65, kitchen=1.6, attic=6.0, drayage=2.0,
                     cartographer=1.8, whispers=2.2, door=2.8,
                     timekeeper=2.0, sentinel=.35, floorboards=1.0)
    dur = 1.8 if failure else durations[fam]
    t = np.arange(round(dur * FS)) / FS
    rng = np.random.default_rng(seed(e["unit"] + verb))
    attack = 1 - np.exp(-t / .004)
    if failure:
        # A single reed buckles, then finds its pitch. It is not an alarm siren.
        inst_f = f * (1 - .17 * np.sin(np.pi * np.minimum(t / 1.2, 1)))
        phase = 2 * np.pi * np.cumsum(inst_f) / FS
        y = (np.sin(phase) + .23 * np.sin(3 * phase)) * np.exp(-t / .48)
        y += .05 * rng.standard_normal(len(t)) * np.exp(-t / .08)
        # The dropped tin cup is part of this one termination, not a second
        # invented system failure.
        n = round(.35 * FS)
        y[n:] += .28 * np.sin(2 * np.pi * 153 * t[:-n]) * np.exp(-t[:-n] / .055)
    elif fam == "clocks":
        y = np.sin(2 * np.pi * f * t + 1.7 * np.sin(2 * np.pi * 2.4 * f * t) * np.exp(-t / .025))
        y *= np.exp(-t / .085)
        y += .08 * rng.standard_normal(len(t)) * np.exp(-t / .006)
    elif fam == "attic":
        y = np.zeros_like(t)
        for ratio, level, decay in [(1, 1, 1.8), (2.01, .47, 1.25), (2.756, .18, .7), (4.07, .07, .35)]:
            y += level * np.sin(2 * np.pi * f * ratio * t) * np.exp(-t / decay)
        if verb == "Finished":
            y += .3 * np.sin(2 * np.pi * 1.5 * f * t) * np.exp(-t / 1.4)
    elif fam == "timekeeper":
        pitch = 880.0 if verb == "Starting" else 1318.51023
        y = np.sin(2 * np.pi * pitch * t) * np.exp(-t / .65)
    elif fam == "sentinel":
        pitch = 720 if verb == "Starting" else 1040
        y = (np.sin(2 * np.pi * pitch * t) + .3 * np.sin(2 * np.pi * pitch * 2.71 * t)) * np.exp(-t / .018)
        y += .1 * rng.standard_normal(len(t)) * np.exp(-t / .007)
    elif fam == "drayage":
        y = (np.sin(2 * np.pi * f * t) + .15 * np.sin(2 * np.pi * f * 2.73 * t)) * np.exp(-t / .2)
        y += .06 * rng.standard_normal(len(t)) * np.exp(-t / .02)
    elif fam in ("door", "whispers"):
        y = sum(a * np.sin(2 * np.pi * f * k * t) * np.exp(-t / d)
                for k, a, d in [(1, 1, .9), (2, .2, .55), (3, .12, .3), (5, .05, .15)])
        y += .055 * np.sin(2 * np.pi * f * 1.003 * t) * np.exp(-t / 1.2)
    elif fam == "cartographer":
        y = (np.sin(2 * np.pi * f * t) + .2 * np.sin(2 * np.pi * f * 3 * t)) * np.exp(-t / .45)
        y += .025 * rng.standard_normal(len(t)) * np.exp(-t / .16)
    elif fam == "kitchen":
        y = sum(np.sin(2 * np.pi * f * k * t) / k ** 1.8 for k in (1, 3, 5, 7))
        y *= np.exp(-t / .35) * (1 + .09 * np.sin(2 * np.pi * 17 * t))
        if verb == "Finished":
            # The kettle's return gets Sparkle-Bird's sweet major third.
            y += .32 * np.sin(2 * np.pi * f * 1.25 * t) * np.exp(-t / .7)
    else:
        y = (np.sin(2 * np.pi * f * t) + .25 * np.sin(2 * np.pi * f * 2.73 * t)) * np.exp(-t / .16)
        y += .09 * rng.standard_normal(len(t)) * np.exp(-t / .016)
    velocity = {"Starting": .48, "Started": .8, "Finished": .95, "Timed out": .62, "Failed to start": .62}[verb]
    return y * attack * velocity * cfg["voices"][fam]["gain"] * e["density_gain"]


def sustained_passages(score: list[dict]) -> list[dict]:
    """Artistic held voices span actual start/finish pairs, not CPU telemetry."""
    starts, spans = {}, []
    for e in score:
        wanted = e["family"] in ("attic", "drayage", "cartographer") or "collider-refresh.service" in e["unit"]
        if not wanted:
            continue
        if e["verb"] == "Starting":
            starts[e["unit"]] = e
        elif e["verb"] == "Finished" and e["unit"] in starts:
            start = starts.pop(e["unit"])
            spans.append(dict(unit=e["unit"], family=e["family"], at_s=start["at_s"],
                              end_s=e["at_s"], hz=start["hz"],
                              real_duration_s=round(e["offset_s"] - start["offset_s"], 6)))
    return spans


def held_voice(span: dict) -> np.ndarray:
    n = max(1, round((span["end_s"] - span["at_s"]) * FS))
    t = np.arange(n) / FS
    f = span["hz"]
    if span["family"] == "drayage":
        y = sum(np.sin(2 * np.pi * f * k * t) / k ** 1.8 for k in range(1, 8))
        y *= .075 * (1 + .15 * np.sin(2 * np.pi * 4.7 * t))
    elif span["family"] == "attic":
        y = .07 * (np.sin(2 * np.pi * f * t) + .6 * np.sin(2 * np.pi * f * 1.006 * t)
                    + .12 * np.sin(2 * np.pi * f * 2.756 * t))
        y *= .8 + .2 * np.sin(2 * np.pi * .19 * t)
    elif span["family"] == "cartographer":
        y = .055 * (np.sin(2 * np.pi * f * t) + .22 * np.sin(2 * np.pi * f * 3 * t)
                    + .18 * np.sin(2 * np.pi * f * 1.5 * t))
        y *= .85 + .15 * np.sin(2 * np.pi * 1.3 * t)
    else:
        y = .045 * (np.sin(2 * np.pi * f * t + .9 * np.sin(2 * np.pi * .23 * t))
                    + .4 * np.sin(2 * np.pi * f * 1.004 * t))
    y *= np.minimum(t / .12, 1) * np.minimum((len(t) / FS - t) / .3, 1)
    angle = np.pi / 4 + .17 * np.sin(2 * np.pi * .15 * t)
    return y[:, None] * np.column_stack([np.cos(angle), np.sin(angle)])


def render(source: dict, cfg: dict) -> tuple[np.ndarray, list[dict], dict]:
    score = make_score(source, cfg)
    length = cfg["lead_in_s"] + cfg["score_s"] + cfg["tail_s"]
    mix = np.zeros((round(length * FS), 2), np.float64)
    for e in score:
        if not e["audible"]:
            continue
        y = instrument(e, cfg)
        start = round(e["at_s"] * FS)
        y = y[:len(mix) - start]
        angle = (e["pan"] + 1) * math.pi / 4
        mix[start:start + len(y), 0] += y * math.cos(angle)
        mix[start:start + len(y), 1] += y * math.sin(angle)
    spans = sustained_passages(score)
    for span in spans:
        start = round(span["at_s"] * FS)
        y = held_voice(span)
        mix[start:start + len(y)] += y
    # A tiny room made from delayed cross-feeds, not a sampled impulse response.
    dry = mix.copy()
    for delay, gain in [(.029, .13), (.053, .095), (.107, .055), (.173, .035)]:
        n = round(delay * FS)
        mix[n:, 0] += gain * dry[:-n, 1]
        mix[n:, 1] += gain * dry[:-n, 0]
    mix = sosfilt(butter(2, 32, btype="highpass", fs=FS, output="sos"), mix, axis=0)
    mix = np.tanh(mix * 1.1)
    mix[-round(1.5 * FS):] *= np.linspace(1, 0, round(1.5 * FS))[:, None]
    mix *= .78 / max(1e-12, float(np.max(np.abs(mix))))
    assert np.isfinite(mix).all()
    stats = dict(sample_rate=FS, duration_s=length, peak=float(np.max(np.abs(mix))),
                 rms=float(np.sqrt(np.mean(mix ** 2))),
                 source_events=len(score), notes=sum(e["audible"] for e in score),
                 sustained_passages=len(spans),
                 source_span_s=max(e["offset_s"] for e in score))
    return mix, score, stats


def main():
    source = json.loads((HERE / "boot-events.json").read_text())
    cfg = json.loads((HERE / "arrangement.json").read_text())
    mix, score, stats = render(source, cfg)
    wavfile.write(HERE / "boot-choir.wav", FS, np.round(mix * 32767).astype(np.int16))
    (HERE / "score.json").write_text(json.dumps(dict(title=cfg["title"], arrangement=cfg,
        source_clock=source["clock"], stats=stats, events=score,
        spans=sustained_passages(score)), indent=2) + "\n")
    (HERE / "render-receipt.json").write_text(json.dumps(stats, indent=2) + "\n")
    print(json.dumps(stats, indent=2))


if __name__ == "__main__":
    main()
