"""Offline, fixture-only all-day boundary experiment; not a general ICS parser."""
from pathlib import Path
from datetime import date,timedelta
import json,sys,platform,tempfile,hashlib,re

def covered_days(raw):
    # Deliberately reject features outside this small teaching subset.
    lines=raw.decode('utf-8').splitlines()
    allowed={'BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//YL//Boundary Lab//EN','BEGIN:VEVENT','END:VEVENT','END:VCALENDAR'}
    if lines[:3]!=['BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//YL//Boundary Lab//EN'] or lines[-2:]!=['END:VEVENT','END:VCALENDAR'] or lines.count('BEGIN:VEVENT')!=1:raise ValueError('unsupported structure')
    props={}
    for line in lines:
        if line in allowed:continue
        key,sep,value=line.partition(':')
        if not sep or key not in {'UID','DTSTAMP','SUMMARY','DTSTART;VALUE=DATE','DTEND;VALUE=DATE'}:raise ValueError('unsupported property or value type')
        if key in props:raise ValueError('duplicate property')
        props[key]=value
    if not {'UID','DTSTAMP','DTSTART;VALUE=DATE'}<=props.keys():raise ValueError('required field missing')
    def parse(v):
        if not re.fullmatch(r'\d{8}',v):raise ValueError('date must be YYYYMMDD')
        return date(int(v[:4]),int(v[4:6]),int(v[6:]))
    start=parse(props['DTSTART;VALUE=DATE']);end=parse(props['DTEND;VALUE=DATE']) if 'DTEND;VALUE=DATE' in props else start+timedelta(days=1)
    count=(end-start).days
    if not 0<count<=366:raise ValueError('end must follow start; teaching limit 366 days')
    return [(start+timedelta(days=i)).isoformat() for i in range(count)]

def fixture(start,end=None,extra=None):
    lines=['BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//YL//Boundary Lab//EN','BEGIN:VEVENT','UID:synthetic@invalid.example','DTSTAMP:20261119T000000Z','SUMMARY:Synthetic holiday','DTSTART;VALUE=DATE:'+start]
    if end is not None:lines.append('DTEND;VALUE=DATE:'+end)
    if extra:lines.append(extra)
    return ('\r\n'.join(lines+['END:VEVENT','END:VCALENDAR'])+'\r\n').encode()

CASES=[
 ('one-day','20261120','20261121',None,['2026-11-20']),
 ('missing-last-day','20261120','20261122',None,['2026-11-20','2026-11-21']),
 ('correct-three-days','20261120','20261123',None,['2026-11-20','2026-11-21','2026-11-22']),
 ('month-boundary','20261130','20261202',None,['2026-11-30','2026-12-01']),
 ('year-boundary','20261231','20270102',None,['2026-12-31','2027-01-01']),
 ('implicit-one-day','20261120',None,None,['2026-11-20']),
 ('equal-end','20261120','20261120',None,None),
 ('mixed-types','20261120',None,'DTEND:20261121T000000Z',None),
 ('recurrence-unsupported','20261120','20261121','RRULE:FREQ=DAILY;COUNT=2',None),
 ('invalid-date','20260230','20260301',None,None),
]

def main():
    results=[]
    with tempfile.TemporaryDirectory(prefix='yl-ics-boundary-') as tmp:
        for name,start,end,extra,expected in CASES:
            p=Path(tmp)/(name+'.ics');p.write_bytes(fixture(start,end,extra));before=hashlib.sha256(p.read_bytes()).hexdigest()
            try:got=covered_days(p.read_bytes());error=None
            except ValueError as e:got=None;error=str(e)
            assert got==expected,(name,got,expected)
            assert before==hashlib.sha256(p.read_bytes()).hexdigest()
            results.append({'case':name,'covered_days':got,'error':error,'passed':True,'source_unchanged':True})
    print(json.dumps({'python':sys.version,'platform':platform.platform(),'actual_calendar_import':False,'cases':results,'passed':True},ensure_ascii=False,indent=2))
if __name__=='__main__':main()
