"""Eight generated weekly series, not a calendar importer or an RFC 5545 engine.

Python 3.9+, standard library and installed timezone data only. No file inputs,
network, calendar access or installation. Output is JSON on standard output.
"""
import datetime as dt
import hashlib
import json
import re
from pathlib import Path
from zoneinfo import ZoneInfo, TZPATH

UTC = dt.timezone.utc
WEEK_MINUTES = 7 * 24 * 60


def parse_local(text):
    if not isinstance(text, str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}', text):
        raise ValueError('Use a local date and whole-minute time without an offset')
    return dt.datetime.fromisoformat(text)


def resolve(naive, zone, ambiguous):
    candidates = []
    for fold in (0, 1):
        aware = naive.replace(tzinfo=zone, fold=fold)
        back = aware.astimezone(UTC).astimezone(zone)
        if back.replace(tzinfo=None) == naive and back.fold == fold:
            candidates.append(aware)
    if not candidates:
        return None
    if len(candidates) > 1:
        if ambiguous == 'reject':
            raise ValueError('Repeated local time needs an occurrence policy')
        return candidates[0 if ambiguous == 'first' else 1]
    return candidates[0]


def minute_gap(a, b):
    # UTC arithmetic, never same-ZoneInfo wall-clock subtraction.
    return int((b.astimezone(UTC) - a.astimezone(UTC)).total_seconds() / 60)


def serialise(items):
    return [dict(occurrence=i+1, local=value.isoformat(timespec='minutes'),
                 utc=value.astimezone(UTC).isoformat(timespec='minutes'),
                 elapsed_since_previous_minutes=None if i == 0 else minute_gap(items[i-1], value))
            for i, value in enumerate(items)]


def compare(start, region, count=4, ambiguous='first', gap='skip'):
    if type(count) is not int or not 2 <= count <= 12:
        raise ValueError('Count must be an integer from 2 to 12')
    if ambiguous not in ('first', 'second', 'reject') or gap not in ('skip', 'reject'):
        raise ValueError('Unknown occurrence or gap policy')
    first_label, zone = parse_local(start), ZoneInfo(region)
    seed = resolve(first_label, zone, ambiguous)
    if seed is None:
        raise ValueError('The first occurrence must exist')
    local, skipped = [], []
    # This bounded teaching model supports weekly series only. Skipped candidates
    # do not count toward the requested accepted occurrences.
    for week in range(count + 12):
        label = first_label + dt.timedelta(days=7*week)
        value = resolve(label, zone, ambiguous)
        if value is None:
            if gap == 'reject':
                raise ValueError('Generated occurrence is in a skipped local hour')
            skipped.append(label.isoformat(timespec='minutes'))
            continue
        local.append(value)
        if len(local) == count:
            break
    if len(local) != count:
        raise ValueError('Bounded weekly search did not find enough occurrences')
    fixed = [(seed.astimezone(UTC) + dt.timedelta(minutes=WEEK_MINUTES*i)).astimezone(zone)
             for i in range(count)]
    return dict(start=start, zone=region, count=count, ambiguous_policy=ambiguous,
                gap_policy=gap, skipped_local_candidates=skipped,
                local_weekly=serialise(local), fixed_168_hours=serialise(fixed))


# UTC endpoints and interval totals are specified independently of the algorithm.
CASES = [
    ('ordinary', '2026-02-01T09:00', 'America/New_York', 'first', [10080,10080,10080], '2026-02-08T14:00+00:00'),
    ('spring', '2026-03-01T09:00', 'America/New_York', 'first', [10020,10080,10080], '2026-03-08T13:00+00:00'),
    ('autumn', '2026-10-25T09:00', 'America/New_York', 'first', [10140,10080,10080], '2026-11-01T14:00+00:00'),
    ('seoul', '2026-03-01T09:00', 'Asia/Seoul', 'first', [10080,10080,10080], '2026-03-08T00:00+00:00'),
    ('skipped', '2026-03-01T02:30', 'America/New_York', 'first', [20100,10080,10080], '2026-03-15T06:30+00:00'),
    ('repeated-first', '2026-10-25T01:30', 'America/New_York', 'first', [10080,10140,10080], '2026-11-01T05:30+00:00'),
    ('repeated-second', '2026-10-25T01:30', 'America/New_York', 'second', [10140,10080,10080], '2026-11-01T06:30+00:00'),
    ('half-hour', '2026-09-27T09:00', 'Australia/Lord_Howe', 'first', [10050,10080,10080], '2026-10-03T22:00+00:00'),
]


def run():
    cases = []
    for identity, start, region, policy, expected, second_utc in CASES:
        row = compare(start, region, ambiguous=policy)
        row['id'] = identity
        actual = [r['elapsed_since_previous_minutes'] for r in row['local_weekly'][1:]]
        assert actual == expected, (identity, actual, expected)
        assert row['local_weekly'][1]['utc'] == second_utc, identity
        for rule in ('local_weekly', 'fixed_168_hours'):
            for a, b in zip(row[rule], row[rule][1:]):
                # A second calculation parses serialized fixed offsets, not ZoneInfo.
                gap = minute_gap(dt.datetime.fromisoformat(a['local']), dt.datetime.fromisoformat(b['local']))
                assert gap == b['elapsed_since_previous_minutes']
                assert gap == minute_gap(dt.datetime.fromisoformat(a['utc']), dt.datetime.fromisoformat(b['utc']))
                if rule == 'fixed_168_hours':
                    assert gap == WEEK_MINUTES
        cases.append(row)
    assert cases[4]['skipped_local_candidates'] == ['2026-03-08T02:30']
    assert cases[4]['local_weekly'][-1]['local'].startswith('2026-03-29T02:30')
    assert cases[1]['fixed_168_hours'][1]['local'].startswith('2026-03-08T10:00')
    assert cases[2]['fixed_168_hours'][1]['local'].startswith('2026-11-01T08:00')
    assert cases[7]['fixed_168_hours'][1]['local'].startswith('2026-10-04T09:30')
    invalid = [
        ('offset-in-local-input', lambda: compare('2026-03-01T09:00+00:00','UTC')),
        ('seconds-not-supported', lambda: compare('2026-03-01T09:00:30','UTC')),
        ('invalid-date', lambda: compare('2026-02-30T09:00','UTC')),
        ('invalid-region', lambda: compare('2026-03-01T09:00','Not/A_Region')),
        ('count-too-large', lambda: compare('2026-03-01T09:00','UTC',13)),
        ('boolean-count', lambda: compare('2026-03-01T09:00','UTC',True)),
        ('unknown-policy', lambda: compare('2026-03-01T09:00','UTC',ambiguous='guess')),
        ('nonexistent-seed', lambda: compare('2026-03-08T02:30','America/New_York')),
        ('unresolved-repeated-time', lambda: compare('2026-10-25T01:30','America/New_York',ambiguous='reject')),
        ('explicit-gap-rejection', lambda: compare('2026-03-01T02:30','America/New_York',gap='reject')),
    ]
    rejected = []
    for identity, check in invalid:
        try:
            check()
        except (ValueError, KeyError) as error:
            rejected.append(dict(id=identity, result='expected_rejection', reason=str(error)))
        else:
            raise AssertionError('Invalid input accepted: '+identity)
    zone_files = []
    for region in sorted({c[2] for c in CASES}):
        for directory in TZPATH:
            file = Path(directory) / region
            if file.is_file():
                zone_files.append(dict(zone=region, sha256=hashlib.sha256(file.read_bytes()).hexdigest()))
                break
    return dict(scope='Eight generated series, four accepted starts per rule; weekly local labels versus 10080 elapsed UTC minutes. Not a full RFC engine, ICS exporter, provider test or meeting-duration model. No private calendar data.',
                policies='Skipped generated local candidates do not consume count. First repeated occurrence is the standard-aligned comparison; second is a separately specified custom choice, not a claim of equivalent RRULE behavior.',
                zone_files=zone_files, cases=cases, invalid_inputs=rejected,
                assertions='Explicit interval totals and second UTC endpoint for each case; serialized-offset/UTC arithmetic for all 48 intervals. Same author, not independent certification.')


if __name__ == '__main__':
    print(json.dumps(run(), ensure_ascii=False, indent=2))
