"""Offline application policy only: no network, waiting, or API feature claims."""
from datetime import datetime, timezone
import json
import math
import re


def finite(value, minimum=0):
    return (type(value) in (int, float) and math.isfinite(value)
            and minimum <= value <= 1_000_000_000_000)


def http_date(header, utc):
    """Strict HTTP-date formats; UTC, including RFC850's rolling year rule.

    Leap seconds are rejected for reconciliation instead of scheduled early.
    """
    short = r'(Mon|Tue|Wed|Thu|Fri|Sat|Sun)'
    long = r'(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)'
    month = r'(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'
    clock = r'([0-9]{2}):([0-9]{2}):([0-9]{2})'
    imf = re.fullmatch(short + r', ([0-9]{2}) ' + month + r' ([0-9]{4}) ' + clock + r' GMT', header)
    old = re.fullmatch(long + r', ([0-9]{2})-' + month + r'-([0-9]{2}) ' + clock + r' GMT', header)
    asc = re.fullmatch(short + r' ' + month + r' ( [1-9]|[0-9]{2}) ' + clock + r' ([0-9]{4})', header)
    if imf or old:
        weekday, day, mon, year, hour, minute, second = (imf or old).groups()
    elif asc:
        weekday, mon, day, hour, minute, second, year = asc.groups()
    else:
        raise ValueError('not a complete HTTP-date')
    year, day, hour, minute, second = map(int, (year, day, hour, minute, second))
    mon = ('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split().index(mon) + 1)
    if old:
        year = utc.year + ((year - utc.year % 100) % 100)
        if (year, mon, day, hour, minute, second) > (utc.year + 50, utc.month, utc.day, utc.hour, utc.minute, utc.second):
            year -= 100
    date = datetime(year, mon, day, hour, minute, second, tzinfo=timezone.utc)
    if weekday[:3] != ('Mon Tue Wed Thu Fri Sat Sun'.split()[date.weekday()]):
        raise ValueError('weekday does not match date')
    return date


def decide(*, status, outcome, replay_safe, attempt, max_attempts, deadline,
           monotonic, utc_now, retry_after=None, call_allowance=5, reserve=1,
           max_wait=10, base_delay=1, jitter=lambda: 0):
    """Return a plan; caller owns scheduling, transport and durable job state.

    attempt includes the original call (1). outcome='rejected' is evidence
    supplied by the caller, never inferred solely from an HTTP status.
    """
    def result(action, reason, wait=0):
        return {'action': action, 'reason': reason, 'wait': wait}

    try:
        now = monotonic()
        utc = utc_now()
        noise = jitter()
        if (type(attempt) is not int or type(max_attempts) is not int
                or not 1 <= attempt <= max_attempts <= 1000
                or type(status) is not int or not 100 <= status <= 599
                or type(replay_safe) is not bool
                or not all(finite(v) for v in (now, deadline, reserve, max_wait))
                or not finite(call_allowance, 0.000001)
                or not finite(base_delay, 0.000001)
                or not finite(noise) or noise > 1
                or not isinstance(utc, datetime) or utc.utcoffset() is None):
            return result('stop', 'invalid_input')
        if outcome != 'rejected' or not replay_safe:
            return result('reconcile', 'outcome_or_replay_uncertain')
        if status not in (429, 503):
            return result('stop', 'nonretryable_status')
        if attempt >= max_attempts:
            return result('stop', 'attempt_limit')
        if retry_after is None:
            # Compare to the cap before exponentiation to avoid overflow.
            if base_delay >= max_wait or attempt - 1 >= math.log2(max_wait / base_delay):
                delay = max_wait
            else:
                delay = base_delay * (2 ** (attempt - 1))
            wait = min(max_wait, delay + delay * noise)
        else:
            try:
                if not isinstance(retry_after, str) or not 1 <= len(retry_after) <= 128:
                    raise ValueError('invalid header length or type')
                if any(ord(char) < 32 or ord(char) == 127 for char in retry_after):
                    raise ValueError('control character in header')
                header = retry_after.strip(' ')
                if header.isascii() and header.isdecimal():
                    wait = int(header)
                else:
                    date = http_date(header, utc.astimezone(timezone.utc))
                    wait = max(0, (date - utc).total_seconds())
                if not finite(wait):
                    raise ValueError('unbounded delay')
            except (ValueError, TypeError, OverflowError):
                return result('stop', 'invalid_retry_after')
        if wait > max_wait:
            return result('defer', 'wait_exceeds_cap', wait)
        if wait + call_allowance + reserve > deadline - now:
            return result('defer', 'deadline', wait)
        return result('retry', 'within_budget', wait)
    except (ValueError, TypeError, OverflowError):
        return result('stop', 'invalid_input')


def demo():
    """Synthetic clocks and response: success means a decision, not generation."""
    return decide(status=429, outcome='rejected', replay_safe=True, attempt=1,
                  max_attempts=3, deadline=120, monotonic=lambda: 100,
                  utc_now=lambda: datetime(2026, 10, 24, tzinfo=timezone.utc),
                  retry_after='2', jitter=lambda: 0.5)


if __name__ == '__main__':
    print(json.dumps(demo(), sort_keys=True))
