import caldav
from caldav import DAVClient
from caldav.elements import dav, cdav
import datetime
import json

# Replace these with your actual Apple ID and application-specific password
APPLE_ID = 'crlsprtrtz@icloud.com'
APP_PASSWORD = 'ewil-jvgj-dvev-qvjc'

# Initialize the client with SSL verification
client = DAVClient(
    url='https://caldav.icloud.com/',
    username=APPLE_ID,
    password=APP_PASSWORD,
    # verify_ssl=True  # Ensure SSL verification is enabled for security
)

# Fetch the principal (iCloud user)
principal = client.principal()

# List all available calendars
calendars = principal.calendars()

# Define the desired calendar name
DESIRED_CALENDAR_NAME = "Trabajo"

# Initialize selected_calendar to None
selected_calendar = None

# Iterate through the calendars to find the desired one
for calendar in calendars:
    if calendar.name.lower() == DESIRED_CALENDAR_NAME.lower():
        selected_calendar = calendar
        break

# Check if the desired calendar was found
if not selected_calendar:
    print(f"Calendar '{DESIRED_CALENDAR_NAME}' not found.")
    exit()

# Define the time range: now to 7 days from now
now = datetime.datetime.now()
in_7_days = now + datetime.timedelta(days=7)

# Fetch events within the specified time range
events = selected_calendar.date_search(
    start=now,
    end=in_7_days
)

# Prepare events for tooltip with enhanced formatting
# Prepare events for tooltip with enhanced formatting and ANSI colors
# Prepare events for tooltip with enhanced formatting and emojis
event_list = []
if events:
    for event in events:
        try:
            event_details = event.vobject_instance
            summary = event_details.vevent.summary.value if hasattr(event_details.vevent, 'summary') else 'No Title'
            dtstart = event_details.vevent.dtstart.value if hasattr(event_details.vevent, 'dtstart') else 'No Start Time'
            
            # Format datetime objects
            if isinstance(dtstart, datetime.datetime):
                dtstart_str = dtstart.strftime('%Y-%m-%d %H:%M')
            elif isinstance(dtstart, datetime.date):
                dtstart_str = dtstart.strftime('%Y-%m-%d') + " (All-Day)"
            else:
                dtstart_str = str(dtstart)
            
            # Adding unicode icons and simple text formatting
            event_list.append(f"📅 {summary}\n  🕒 {dtstart_str}")
        
        except Exception as e:
            continue

# Create the output JSON for Waybar with formatted tooltip
output = {
    "text": now.strftime('%Y-%m-%d %H:%M'),
    "tooltip": "\n\n".join(event_list) if event_list else "No events in the next 7 days",
    "class": "calendar"
}

# Output JSON
print(json.dumps(output))

