"""Fixed fictional calendar cases; no personal calendars, files or network."""
from collections import Counter
from datetime import datetime, timezone
import copy
import json
import re


def parse(value):
    if not isinstance(value, str) or not re.fullmatch(
            r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})', value):
        raise ValueError('Expected a dated, whole-minute timestamp with explicit UTC offset')
    return datetime.fromisoformat(value.replace('Z', '+00:00')).astimezone(timezone.utc)


def measure(case):
    start, end = parse(case['start']), parse(case['end'])
    width = int((end - start).total_seconds() // 60)
    if not 0 < width <= 1440:
        raise ValueError('Window must be positive and at most 1440 minutes')
    seen, rows, clipped = set(), [], []
    for event in case['events']:
        identity = event['id']
        if not isinstance(identity, str) or not identity or identity in seen:
            raise ValueError('Event IDs must be nonempty and distinct')
        seen.add(identity)
        a, b = parse(event['start']), parse(event['end'])
        if a >= b:
            raise ValueError('End must follow start; midnight does not imply the next day')
        x, y = max(start, a), min(end, b)
        minutes = max(0, int((y - x).total_seconds() // 60))
        rows.append(dict(event, raw_minutes=int((b-a).total_seconds()//60), clipped_minutes=minutes))
        if minutes:
            clipped.append((int((x-start).total_seconds()//60), int((y-start).total_seconds()//60), identity))
    merged = []
    for a, b, _ in sorted(clipped):
        if merged and a <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], b)
        else:
            merged.append([a, b])
    gaps, cursor = [], 0
    for a, b in merged:
        if cursor < a:
            gaps.append([cursor, a])
        cursor = b
    if cursor < width:
        gaps.append([cursor, width])
    boundaries = sorted({0, width, *(x for a, b, _ in clipped for x in (a, b))})
    segments = []
    for a, b in zip(boundaries, boundaries[1:]):
        active = sorted(identity for x, y, identity in clipped if x <= a < y)
        segments.append({'start_minute':a, 'end_minute':b, 'active_ids':active})
    summed = sum(row['clipped_minutes'] for row in rows)
    occupied = sum(b-a for a,b in merged)
    conflict = sum(s['end_minute']-s['start_minute'] for s in segments if len(s['active_ids']) >= 2)
    excess = sum((len(s['active_ids'])-1)*(s['end_minute']-s['start_minute']) for s in segments if s['active_ids'])
    peak = max((len(s['active_ids']) for s in segments), default=0)
    # Separate finite oracle: enumerate each minute instead of merging intervals.
    minute_counts = Counter(minute for a,b,_ in clipped for minute in range(a,b))
    assert occupied == len(minute_counts)
    assert conflict == sum(n >= 2 for n in minute_counts.values())
    assert excess == sum(n-1 for n in minute_counts.values()) == summed-occupied
    assert peak == max(minute_counts.values(), default=0)
    assert sum(b-a for a,b in gaps)+occupied == width
    result = {'id':case['id'], 'start':case['start'], 'end':case['end'], 'rows':rows,
              'window_minutes':width, 'raw_sum_minutes':sum(r['raw_minutes'] for r in rows),
              'clipped_sum_minutes':summed, 'occupied_minutes':occupied,
              'conflict_minutes':conflict, 'extra_counted_minutes':excess, 'peak_events':peak,
              'unoccupied_minutes':width-occupied, 'longest_gap_minutes':max((b-a for a,b in gaps),default=0),
              'merged_offsets':merged, 'gap_offsets':gaps, 'segments':segments,
              'minute_oracle':'matched; whole-minute fixed-offset cases only'}
    for key, expected in case.get('expected', {}).items():
        assert result[key] == expected, (case['id'], key, result[key], expected)
    return result


def event(identity, start, end):
    return {'id':identity, 'start':start, 'end':end}


def at(time):
    return '2026-10-24T'+time+'+09:00'


CASES = [
    {'id':'overlap', 'start':at('09:00'), 'end':at('17:00'), 'events':[
        event('A',at('09:00'),at('09:30')), event('B',at('09:30'),at('11:00')),
        event('C',at('10:15'),at('10:45')), event('D',at('10:30'),at('11:15')),
        event('E',at('12:00'),at('13:00')), event('F',at('16:15'),at('17:30'))],
     'expected':{'raw_sum_minutes':330, 'clipped_sum_minutes':300, 'occupied_minutes':240,
                 'conflict_minutes':45, 'extra_counted_minutes':60, 'peak_events':3,
                 'unoccupied_minutes':240, 'longest_gap_minutes':195}},
    {'id':'adjacent', 'start':at('09:00'), 'end':at('11:00'), 'events':[
        event('A',at('09:30'),at('10:00')),event('B',at('10:00'),at('10:30'))],
     'expected':{'clipped_sum_minutes':60,'occupied_minutes':60,'conflict_minutes':0,'unoccupied_minutes':60,'longest_gap_minutes':30}},
    {'id':'overnight', 'start':at('23:00'), 'end':'2026-10-25T02:00+09:00','events':[
        event('A',at('23:30'),'2026-10-25T00:30+09:00'),
        event('B','2026-10-25T00:15+09:00','2026-10-25T01:15+09:00')],
     'expected':{'window_minutes':180,'clipped_sum_minutes':120,'occupied_minutes':105,'conflict_minutes':15,'unoccupied_minutes':75,'longest_gap_minutes':45}},
    {'id':'same_instant_different_offsets','start':at('09:00'),'end':at('10:00'),'events':[
        event('A',at('09:00'),at('09:30')),event('B','2026-10-24T00:00Z','2026-10-24T00:30Z')],
     'expected':{'clipped_sum_minutes':60,'occupied_minutes':30,'conflict_minutes':30,'unoccupied_minutes':30}},
    {'id':'empty','start':at('09:00'),'end':at('10:00'),'events':[],
     'expected':{'clipped_sum_minutes':0,'occupied_minutes':0,'conflict_minutes':0,'unoccupied_minutes':60,'longest_gap_minutes':60}},
    {'id':'outside','start':at('09:00'),'end':at('10:00'),'events':[
        event('A',at('08:00'),at('09:00')),event('B',at('10:00'),at('11:00'))],
     'expected':{'raw_sum_minutes':120,'clipped_sum_minutes':0,'occupied_minutes':0,'conflict_minutes':0,'unoccupied_minutes':60}},
]

repaired = copy.deepcopy(CASES[0])
repaired.update(id='repaired', expected={'clipped_sum_minutes':300,'occupied_minutes':300,
                'conflict_minutes':0,'unoccupied_minutes':180,'longest_gap_minutes':120})
repaired['events'][2].update(start=at('13:00'),end=at('13:30'))
repaired['events'][3].update(start=at('13:30'),end=at('14:15'))
CASES.append(repaired)


def run():
    scenarios = [measure(case) for case in CASES]
    overnight = CASES[2]
    before_midnight = measure(dict(overnight, end='2026-10-25T00:00+09:00', expected={}))
    after_midnight = measure(dict(overnight, start='2026-10-25T00:00+09:00', expected={}))
    assert (before_midnight['occupied_minutes'],after_midnight['occupied_minutes']) == (30,75)
    assert before_midnight['occupied_minutes']+after_midnight['occupied_minutes'] == scenarios[2]['occupied_minutes']
    invalid=[]
    mutations = [
        ('missing_offset',lambda c:c['events'][0].update(start='2026-10-24T09:00')),
        ('seconds_precision',lambda c:c['events'][0].update(start='2026-10-24T09:00:30+09:00')),
        ('invalid_date',lambda c:c['events'][0].update(start='2026-02-30T09:00+09:00')),
        ('zero_duration',lambda c:c['events'][0].update(end=c['events'][0]['start'])),
        ('reversed_end',lambda c:c['events'][0].update(end=at('08:59'))),
        ('duplicate_id',lambda c:c['events'][1].update(id='A')),
        ('missing_end',lambda c:c['events'][0].pop('end')),
        ('reversed_window',lambda c:c.update(end=at('08:00'))),
        ('window_over_24h',lambda c:c.update(end='2026-10-25T09:01+09:00')),
    ]
    for name, mutate in mutations:
        broken=copy.deepcopy(CASES[0]); mutate(broken)
        try: measure(broken)
        except (ValueError,KeyError,TypeError) as error: invalid.append({'case':name,'result':'rejected_as_expected','reason':str(error)})
        else: raise AssertionError('Invalid input accepted: '+name)
    return {'scope':'Generated events only; half-open intervals, explicit fixed offsets, whole minutes. No recurring events, named-zone DST resolution or personal calendars.',
            'scenarios':scenarios, 'midnight_split_occupied_minutes':[30,75], 'invalid_inputs':invalid}


if __name__ == '__main__':
    print(json.dumps(run(),indent=2,ensure_ascii=False))
