"""Phase 3 release scheduler: pick a millisecond-jittered timestamp inside the
next Tue 9-11am US Pacific OR Wed 9-11am CET window.

Returns tz-aware datetimes. The choice between Tue-Pacific and Wed-CET is
random (seedable via the injected `rng` for tests).
"""
import random
import zoneinfo
from datetime import datetime, time, timedelta

PACIFIC = zoneinfo.ZoneInfo("America/Los_Angeles")
CET = zoneinfo.ZoneInfo("Europe/Berlin")
WINDOW_DURATION_MS = 2 * 60 * 60 * 1000  # 2 hours
PACIFIC_WEEKDAY = 1  # Tuesday (Monday=0)
CET_WEEKDAY = 2      # Wednesday
WINDOW_START_HOUR = 9


def _next_window_start(now: datetime, tz: zoneinfo.ZoneInfo, weekday: int) -> datetime:
    """Return the next datetime at 9:00 local in `tz` on the given weekday strictly after `now`."""
    now_local = now.astimezone(tz)
    days_ahead = (weekday - now_local.weekday()) % 7
    candidate = now_local.replace(hour=WINDOW_START_HOUR, minute=0, second=0, microsecond=0) + timedelta(days=days_ahead)
    if candidate <= now_local:
        candidate += timedelta(days=7)
    return candidate


def next_peak_timestamp(now: datetime, rng: random.Random) -> datetime:
    pacific_start = _next_window_start(now, PACIFIC, PACIFIC_WEEKDAY)
    cet_start = _next_window_start(now, CET, CET_WEEKDAY)
    chosen_start = rng.choice([pacific_start, cet_start])
    offset_ms = rng.uniform(0, WINDOW_DURATION_MS)
    return chosen_start + timedelta(milliseconds=offset_ms)
