"""Create local date reminders from an actual observed Teams expiry date.
Python 3, standard library only. No Teams API or retention calculation.
Usage: python recording-reminders.py 2026-11-06 --title "Training recording"
"""
import argparse
import hashlib
from datetime import date, datetime, timedelta, timezone
from pathlib import Path


def text(value):
    return value.replace('\\', '\\\\').replace('\n', '\\n').replace(';', '\\;').replace(',', '\\,')


def fold(line):
    parts, current, length = [], '', 0
    for char in line:
        size = len(char.encode('utf-8'))
        if length + size > 75:
            parts.append(current)
            current, length = ' ', 1
        current += char
        length += size
    parts.append(current)
    return '\r\n'.join(parts)


def calendar(expiry, title, created=None):
    created = created or datetime.now(timezone.utc)
    stamp = created.strftime('%Y%m%dT%H%M%SZ')
    lines = ['BEGIN:VCALENDAR', 'VERSION:2.0',
             'PRODID:-//HowCurio//Recording reminders//EN', 'CALSCALE:GREGORIAN']
    for offset, task in ((7, 'Review access and permitted retention'), (1, 'Confirm recording handoff')):
        day = expiry - timedelta(days=offset)
        key = hashlib.sha256(f'{expiry.isoformat()}:{title}:{offset}'.encode()).hexdigest()[:24]
        lines.extend(['BEGIN:VEVENT', f'UID:{key}@howcurio.com', f'DTSTAMP:{stamp}',
                      f'DTSTART;VALUE=DATE:{day:%Y%m%d}',
                      f'DTEND;VALUE=DATE:{day + timedelta(days=1):%Y%m%d}',
                      'TRANSP:TRANSPARENT', f'SUMMARY:{text(title + ": " + task)}',
                      'DESCRIPTION:Local reminder only. Recheck the actual hosted expiry and permissions.',
                      'END:VEVENT'])
    lines.append('END:VCALENDAR')
    return '\r\n'.join(fold(line) for line in lines) + '\r\n'


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('expiry', help='Observed hosted expiry, YYYY-MM-DD')
    parser.add_argument('--title', default='Teams recording', help='Avoid confidential meeting names')
    parser.add_argument('--output', default='recording-reminders.ics')
    args = parser.parse_args()
    try:
        expiry = date.fromisoformat(args.expiry)
        if expiry.isoformat() != args.expiry:
            raise ValueError('Use YYYY-MM-DD')
        if any(ord(c) < 32 for c in args.title) or len(args.title) > 160:
            raise ValueError('Title must be 1 to 160 printable characters')
        if not args.title.strip():
            raise ValueError('Title cannot be empty')
        output = Path(args.output)
        with output.open('x', encoding='utf-8', newline='') as handle:
            handle.write(calendar(expiry, args.title))
        print(f'Created {output}. Review both dates before importing. No Teams setting changed.')
    except (OSError, ValueError) as error:
        parser.exit(2, f'Cannot create reminders: {error}\n')
