"""Compare NOAA high-tide intervals with the period of M2."""
import argparse
import json
import math
import platform
import sys
from datetime import datetime, timezone
from decimal import Decimal
from pathlib import Path


def summarize(station):
    highs_by_day = {}
    previous = None
    for row in station["predictions"]:
        moment = datetime.strptime(row["t"], "%Y-%m-%d %H:%M").replace(tzinfo=timezone.utc)
        if previous is not None and moment <= previous:
            raise ValueError("prediction rows must be in strictly increasing order")
        previous = moment
        daily_highs = highs_by_day.setdefault(moment.date(), [])
        if row["type"] == "H":
            daily_highs.append((moment, row["v"]))
        elif row["type"] != "L":
            raise ValueError("unknown tide type")

    days = sorted(highs_by_day)
    if not days or any(len(highs_by_day[day]) != 2 for day in days):
        raise ValueError("rank comparisons require exactly two highs per UTC date")
    if any((b - a).days != 1 for a, b in zip(days, days[1:])):
        raise ValueError("rank comparisons require consecutive UTC dates")
    day_pairs = [highs_by_day[day] for day in days]
    highs = [moment for day in day_pairs for moment, _ in day]
    adjacent = [int((b - a).total_seconds() / 60) for a, b in zip(highs, highs[1:])]
    shifts = []
    for before, after in zip(day_pairs, day_pairs[1:]):
        shifts.append([int((b - a).total_seconds() / 60) - 24 * 60
                       for (a, _), (b, _) in zip(before, after)])
    return {
        "station": station["station"],
        "dates_utc": [day.isoformat() for day in days],
        "highs_utc_and_m": [[[moment.strftime("%H:%M"), height]
                             for moment, height in day] for day in day_pairs],
        "adjacent_high_gaps_minutes": adjacent,
        "same_daily_rank_later_minutes": shifts,
        "same_daily_rank_minus_50_minute_rule": [[shift - 50 for shift in pair] for pair in shifts],
        "first_day_high_difference_m": str(abs(Decimal(day_pairs[0][0][1]) -
                                                 Decimal(day_pairs[0][1][1]))),
    }


def run(snapshot):
    speed = 28.9841042
    m2_hours = 360 / speed
    lunar_day = 2 * m2_hours
    drift = (lunar_day - 24) * 60
    m2_s2_alignment_days = 360 / (30 - speed) / 24
    amplitude = 0.4
    phase = math.asin(amplitude / 4)
    shift = lunar_day * phase / math.tau
    # y = cos(2θ) + 0.4 sin(θ). At both maxima sin(θ) = 0.1.
    shorter, longer = m2_hours - 2 * shift, m2_hours + 2 * shift
    assert math.isclose(shorter + longer, lunar_day)
    assert abs(-2 * math.sin(2 * phase) + amplitude * math.cos(phase)) < 1e-12
    assert -4 * math.cos(2 * phase) - amplitude * math.sin(phase) < 0
    assert math.isclose(math.cos(2 * phase) + amplitude * math.sin(phase), 1.02)
    summaries = [summarize(station) for station in snapshot["stations"]]
    assert [row["same_daily_rank_later_minutes"] for row in summaries] == [
        [[49, 39], [52, 45]], [[39, 43], [54, 48]],
    ]
    assert [row["adjacent_high_gaps_minutes"] for row in summaries] == [
        [595, 894, 585, 907, 578], [795, 684, 799, 695, 793],
    ]
    first_station = snapshot["stations"][0]
    incomplete = {**first_station, "predictions": first_station["predictions"][0:3]}
    try:
        summarize(incomplete)
    except ValueError as error:
        incomplete_error = str(error)
    else:
        raise AssertionError("an incomplete day was accepted for the rank comparison")
    return {
        "environment": {"os": platform.system(), "os_version": platform.mac_ver()[0] or platform.release(),
                        "machine": platform.machine(), "python": sys.version.split()[0]},
        "m2_speed_degrees_per_hour": speed,
        "m2_period_hours": round(m2_hours, 8),
        "two_m2_cycles_hours": round(lunar_day, 8),
        "two_m2_cycles_minus_one_day_minutes": round(drift, 6),
        "m2_s2_alignment_days": round(m2_s2_alignment_days, 6),
        "synthetic_mixed_high_gaps_hours": [round(shorter, 6), round(longer, 6)],
        "stations": summaries,
        "incomplete_day_error": incomplete_error,
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("snapshot", type=Path)
    args = parser.parse_args()
    print(json.dumps(run(json.loads(args.snapshot.read_text())), indent=2))
