import os
import yaml
import subprocess
from caldav import DAVClient
from ics import Calendar, Todo
from datetime import datetime, timedelta

def get_password(user_cfg):
    if 'password_cmd' in user_cfg:
        return subprocess.check_output(user_cfg['password_cmd'], shell=True).decode().strip()
    return user_cfg.get('password')

def add_event(calendar, summary, classification, start_hour):
    now = datetime.now()
    dtstamp = now.strftime("%Y%m%dT%H%M%SZ")
    dtstart = (now.replace(hour=start_hour, minute=0, second=0)).strftime("%Y%m%dT%H%M%SZ")
    dtend = (now.replace(hour=start_hour+1, minute=0, second=0)).strftime("%Y%m%dT%H%M%SZ")

    print(f"Adding {classification} event: {summary} at {start_hour}:00")
    calendar.add_event(f"""BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp//CalDAV Client//EN
BEGIN:VEVENT
UID:uid-{summary.lower().replace(' ', '-')}-{classification.lower()}
DTSTAMP:{dtstamp}
DTSTART:{dtstart}
DTEND:{dtend}
SUMMARY:{summary}
CLASS:{classification}
END:VEVENT
END:VCALENDAR""")

def add_todo(calendar, summary, classification):
    now = datetime.now()
    dtstamp = now.strftime("%Y%m%dT%H%M%SZ")
    print(f"Adding {classification} todo: {summary}")
    calendar.save_todo(f"""BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp//CalDAV Client//EN
BEGIN:VTODO
UID:todo-{summary.lower().replace(' ', '-')}-{classification.lower()}
DTSTAMP:{dtstamp}
SUMMARY:{summary}
CLASS:{classification}
END:VTODO
END:VCALENDAR""")

if __name__ == "__main__":
    with open("config.yaml") as f:
        config = yaml.safe_load(f)

    url = "http://localhost:8080/"
    
    alice_cfg = next(u for u in config['users'] if u['name'] == 'alice')
    alice_pw = get_password(alice_cfg)
    alice_client = DAVClient(url, username=alice_cfg['name'], password=alice_pw)
    alice_principal = alice_client.principal()
    alice_personal = next(c for c in alice_principal.calendars() if "personal" in c.url.path)

    print("\n--- Alice creating items for TODAY ---")
    add_event(alice_personal, "Public Dinner", "PUBLIC", 18)
    add_event(alice_personal, "Confidential Meeting", "CONFIDENTIAL", 14)
    add_todo(alice_personal, "Secret Task", "PRIVATE")
    add_todo(alice_personal, "Sensitive Project", "CONFIDENTIAL")

    bob_cfg = next(u for u in config['users'] if u['name'] == 'bob')
    bob_pw = get_password(bob_cfg)
    bob_client = DAVClient(url, username=bob_cfg['name'], password=bob_pw)
    bob_principal = bob_client.principal()
    
    print("\n--- Bob viewing Alice's calendar ---")
    bob_alice_personal = next(c for c in bob_principal.calendars() if "/alice/calendars/personal/" in c.url.path)

    print("Checking Events...")
    events = bob_alice_personal.events()
    for e in events:
        c = Calendar(e.data)
        for ev in c.events:
            print(f" - Event: '{ev.name}' (UID: {ev.uid})")

    print("Checking Todos...")
    todos = bob_alice_personal.todos()
    for t in todos:
        c = Calendar(t.data)
        for td in c.todos:
            print(f" - Todo: '{td.name}' (UID: {td.uid})")
