#!/usr/bin/env python3
"""
06_flood_2026.py — the sky over the Trishuli, 26 August – 1 September 2026.

The Langtang Lirung glacier collapse of 26 Aug 2026 (08:37 NPT = 02:52 UTC,
registered as a Ms 5.2 seismic event) sent a debris flood down the Lhende
Khola and the Trishuli; a barrier lake overflowed on 28 Aug; new flood
warnings followed increased upstream flow on 30 Aug; a controlled
explosion opened the Upper Trishuli 3A tunnel in the early hours of 31 Aug.

For each stage this script gives the Moon's sidereal nakṣatra and its
Bṛhat Saṁhitā 32 circle, the tithi, the full graha set and a North-Indian
chart (SVG) cast for Rasuwagadhi (28.28 N, 85.38 E).  It also tabulates the
Moon's nakṣatra every hour across the week so the essay can draw the strip.

Output: flood_2026.json, chart_*.svg
"""
import json

import numpy as np
import pandas as pd
import swisseph as swe

import bhukampa_common as bc

LAT, LON = 28.28, 85.38          # Rasuwagadhi / Gyirong Port
STAGES = [
    ("collapse", "2026-08-26T02:52:00Z", "Glacier collapse on Langtang Lirung; Ms 5.2 seismic signal; Gyirong Port destroyed seven minutes later"),
    ("second", "2026-08-26T05:52:00Z", "Second landslide signal, Ms 4.2, three hours after the first"),
    ("lake", "2026-08-28T06:15:00Z", "Barrier lake near the Chhochen Khola–Purepu Tsangpo confluence overflows; rescue halted three hours"),
    ("warning", "2026-08-30T06:15:00Z", "Flood-warning notices after increased upstream flow; lake largely drained"),
    ("tunnel", "2026-08-30T21:15:00Z", "Controlled explosion opens the Upper Trishuli 3A tunnel (early hours of 31 Aug NPT)"),
]
SIGNS = ["Meṣa", "Vṛṣabha", "Mithuna", "Karkaṭa", "Siṁha", "Kanyā", "Tulā",
         "Vṛścika", "Dhanus", "Makara", "Kumbha", "Mīna"]
ABBR = {"Sun": "Sy", "Moon": "Ch", "Mars": "Ma", "Mercury": "Bu", "Jupiter": "Gu",
        "Venus": "Śu", "Saturn": "Śa", "Rāhu": "Ra", "Ketu": "Ke"}


def jd_of(iso):
    return float(bc.julian_days(pd.Series([iso]))[0])


def dms(x):
    d = int(x); m = int((x - d) * 60)
    return f"{d}°{m:02d}′"


def chart_svg(pos, asc, title, sub, moon_nak, moon_circle):
    """North Indian chart, 420×440, house 1 = top diamond, counter-clockwise."""
    S = 400
    asc_sign = int(asc // 30)
    # house polygons (centre points for labels)
    C = S / 2
    # planet-text centres (centroids of the twelve cells) and sign-number spots (near each cell's inner vertex)
    P = {1: (C, S * 0.22), 2: (S * 0.25, S * 0.09), 3: (S * 0.09, S * 0.25), 4: (S * 0.22, C),
         5: (S * 0.09, S * 0.75), 6: (S * 0.25, S * 0.91), 7: (C, S * 0.78), 8: (S * 0.75, S * 0.91),
         9: (S * 0.91, S * 0.75), 10: (S * 0.78, C), 11: (S * 0.91, S * 0.25), 12: (S * 0.75, S * 0.09)}
    SN = {1: (C, S * 0.45), 2: (S * 0.27, S * 0.215), 3: (S * 0.215, S * 0.27), 4: (S * 0.45, C),
          5: (S * 0.215, S * 0.73), 6: (S * 0.27, S * 0.785), 7: (C, S * 0.55), 8: (S * 0.73, S * 0.785),
          9: (S * 0.785, S * 0.73), 10: (S * 0.55, C), 11: (S * 0.785, S * 0.27), 12: (S * 0.73, S * 0.215)}
    lines = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 {S+8} {S+48}" width="{S+8}" height="{S+48}" font-family="Lato, system-ui, sans-serif">',
             f'<rect x="-4" y="-4" width="{S+8}" height="{S+48}" fill="#0b0e18"/>',
             f'<rect x="0" y="0" width="{S}" height="{S}" fill="#101526" stroke="#d4af37" stroke-width="1.2"/>',
             f'<path d="M0 0 L{S} {S} M{S} 0 L0 {S} M{C} 0 L{S} {C} L{C} {S} L0 {C} Z" fill="none" stroke="#d4af37" stroke-width="1"/>']
    houses = {h: [] for h in range(1, 13)}
    for g, lon in pos.items():
        h = ((int(lon // 30) - asc_sign) % 12) + 1
        houses[h].append((g, lon))
    for h in range(1, 13):
        sign = (asc_sign + h - 1) % 12
        sx, sy = SN[h]
        lines.append(f'<text x="{sx:.0f}" y="{sy:.0f}" text-anchor="middle" font-size="11" fill="#8a93ad">{sign+1}</text>')
        x, y = P[h]
        items = houses[h]
        if h == 1:
            items = [("Lg", asc)] + items
        n = len(items)
        for i, (g, lon) in enumerate(items):
            dy = (i - (n - 1) / 2) * 15
            fill = "#f5f0e8"
            if g == "Moon":
                fill = "#7fb3ff"
            elif g == "Lg":
                fill = "#d4af37"
            lines.append(f'<text x="{x:.0f}" y="{y+dy+4:.0f}" text-anchor="middle" font-size="12.5" '
                         f'fill="{fill}" font-weight="{700 if g=="Moon" else 400}">{ABBR.get(g,g)} {dms(lon%30)}</text>')
    lines.append(f'<text x="{C}" y="{S+18}" text-anchor="middle" font-size="13" fill="#d4af37" font-family="Cormorant Garamond, Georgia, serif" font-weight="700">{title}</text>')
    lines.append(f'<text x="{C}" y="{S+36}" text-anchor="middle" font-size="11.5" fill="#f5f0e8" fill-opacity="0.8">Moon in {moon_nak} · {moon_circle} circle</text>')
    lines.append("</svg>")
    return "\n".join(lines)


def main():
    out = {"place": {"lat": LAT, "lon": LON, "name": "Rasuwagadhi / Gyirong Port"}, "stages": []}
    for key, iso, desc in STAGES:
        jd = jd_of(iso)
        pos = bc.planet_sidereal_longitudes(jd)
        asc = bc.ascendant_sidereal(jd, LAT, LON)
        m = pos["Moon"]
        n27 = bc.NAK27[int(bc.nak27_index(m))]
        n28 = bc.NAK28[int(bc.nak28_index(m))]
        tithi = int(((m - pos["Sun"]) % 360) // 12) + 1
        npt = (pd.Timestamp(iso) + pd.Timedelta(hours=5, minutes=45)).strftime("%d %b %Y %H:%M")
        st = {"key": key, "utc": iso, "npt": npt + " NPT", "desc": desc,
              "moon_lon": round(m, 3), "nak27": n27, "nak28": n28,
              "pada": int((m % (360 / 27)) // (360 / 108)) + 1,
              "mandala": bc.MANDALA_OF[n28], "tithi": tithi,
              "asc": round(asc, 2), "asc_sign": SIGNS[int(asc // 30)],
              "moon_sign": SIGNS[int(m // 30)],
              "positions": {k: round(v, 3) for k, v in pos.items()}}
        out["stages"].append(st)
        svg = chart_svg(pos, asc, npt + " NPT · Rasuwagadhi", desc.split(";")[0], n28, st["mandala"])
        open(f"chart_{key}.svg", "w", encoding="utf-8").write(svg)
        print(f"{key:9s} {npt} NPT  Moon {m:7.2f}° {n28:16s} pāda {st['pada']}  {st['mandala']:6s} circle  tithi {tithi}  Lagna {SIGNS[int(asc//30)]} {dms(asc%30)}")

    # hourly strip 25 Aug 18:15 UTC (26 Aug 00:00 NPT) → 1 Sep 18:15 UTC
    t = pd.date_range("2026-08-25T18:15:00Z", "2026-09-01T18:15:00Z", freq="1h")
    lon = bc.moon_sidereal_longitude(bc.julian_days(pd.Series(t)))
    strip = []
    prev = None
    for ts, l in zip(t, lon):
        n = bc.NAK28[int(bc.nak28_index(l))]
        if n != prev:
            strip.append({"utc": ts.isoformat(), "nak28": n, "mandala": bc.MANDALA_OF[n]})
            prev = n
    out["strip"] = strip
    # exact transition times (bisection to the minute)
    trans = []
    for i in range(1, len(lon)):
        if bc.nak28_index(lon[i]) != bc.nak28_index(lon[i - 1]):
            a, b = t[i - 1], t[i]
            for _ in range(12):
                mid = a + (b - a) / 2
                lm = bc.moon_sidereal_longitude(bc.julian_days(pd.Series([mid])))[0]
                if bc.nak28_index(lm) == bc.nak28_index(lon[i - 1]):
                    a = mid
                else:
                    b = mid
            trans.append({"utc": b.isoformat(), "enter": bc.NAK28[int(bc.nak28_index(lon[i]))]})
    out["transitions"] = trans
    json.dump(out, open("flood_2026.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    for tr in trans:
        print("  →", tr["utc"], tr["enter"], bc.MANDALA_OF[tr["enter"]])


if __name__ == "__main__":
    main()
