# Screen Walker designs on two orbits, then confirm the best three over 24 hours.
# Run with:
#   program_run {project, name: "Walker screen", inputs: {grid: <cells layer>}, source: <this file>}
# The grid is a cells layer bound to data over the region that matters: data_put rows or CSV with an H3 cell column.
# A grid drawn in the window (an h3-grid entity, such as a whole-Earth grid) is refused as a program input.
# Each Engine call in a program stops after 30 s, and a run has 300 s of Engine time on Pro. A coverage with radio
# refraction computed about 4 million elevations a CPU second on one core, so each call here stays under 60 million
# elevations (about 15 s) and the 12 coverages under 720 million (about 3 minutes). Up to 26 cells keep a 60 s step
# throughout (26 x 1,584 x 1,441 = 59 million); a larger grid gets a coarser step (each row's step_s says which), and
# past about 18,900 cells nothing fits: run each design as its own compute instead.
# Units: altitude km, inclination deg, mask deg, times s, coverage a fraction 0 to 1.
# 24 explicit Engine calls, plus retained propagation: check Engine time and daily quota before running.
import math

import pandas as pd

p = dk.params(
    altitudes=[500, 550, 600],  # km
    inclinations=[50, 53, 56],  # deg
    planes=72,
    per_plane=22,
    phasing=17,
    min_elevation=25,  # deg
    keep=3,  # designs confirmed over 24 h
)
grid = dk.layer("grid")

MU, RE = 398600.4418, 6378.137  # km^3/s^2, km (WGS 84)
CALL_MAX = 60_000_000  # cells x satellites x instants per coverage call, inside a program call's 30 s
total = p["planes"] * p["per_plane"]
if grid.rows * total * 2 > CALL_MAX:
    raise ValueError(f"{grid.rows} cells x {total} satellites leave fewer than 2 instants a call: use fewer cells")


def period_s(altitude_km):
    return 2 * math.pi * math.sqrt((RE + altitude_km) ** 3 / MU)


def step_that_fits(duration_s):
    # The smallest whole-minute step that keeps the coverage call inside a program call's time.
    instants_max = CALL_MAX // (grid.rows * total)
    return max(60, 60 * math.ceil(duration_s / max(instants_max - 1, 1) / 60))


def coverage(altitude, inclination, duration_s):
    fleet = dk.engine.walker(total=total, planes=p["planes"], phasing=p["phasing"],
                             altitude=altitude, inclination=inclination)
    step = step_that_fits(duration_s)
    cells = dk.engine.grid_coverage(fleet, grid=grid, min_elevation=p["min_elevation"],
                                    start=dk.clock.start, duration=duration_s, step=step).cells.df()
    return {"altitude": altitude, "inclination": inclination, "duration_s": round(duration_s), "step_s": step,
            "min_coverage": float(cells.coverage_fraction.min()),
            "mean_coverage": float(cells.coverage_fraction.mean()),
            "worst_gap_s": float(cells.longest_gap.max())}


# Screen: a Walker's band coverage repeats each orbit, so two periods rank the designs.
screen = pd.DataFrame([coverage(a, i, 2 * period_s(a)) for a in p["altitudes"] for i in p["inclinations"]])
screen = screen.sort_values(["min_coverage", "mean_coverage"], ascending=False)

# Confirm: only the 24 h numbers are a result.
confirmed = pd.DataFrame([coverage(r.altitude, r.inclination, 86400) for r in screen.head(p["keep"]).itertuples()])

units = {"altitude": "km", "inclination": "deg", "duration_s": "s", "step_s": "s",
         "min_coverage": "1", "mean_coverage": "1", "worst_gap_s": "s"}
dk.emit.table(screen, slot="table", title="Screen: two orbits", units=units)
dk.emit.table(confirmed, slot="table_2", title="Confirmed: 24 h", units=units)
dk.emit.chart(slot="table", x="inclination", y=["min_coverage", "mean_coverage"], kind="scatter")
dk.result({"winner": confirmed.sort_values("min_coverage", ascending=False).head(1).to_dict("records"),
           "satellites": total, "mask_deg": p["min_elevation"]})
print("screened", len(screen), "confirmed", len(confirmed))
