#!/usr/bin/env python3
"""Morning briefing template — copy and modify.

Reads credentials from env vars (NEVER hardcode passwords).
Expected .env entries:
  APPLE_EMAIL="your@icloud.com"
  APPLE_APP_PASSWORD="xxxx-xxxx-xxxx-xxxx"

Requires: python3 -m pip install caldav vobject feedparser
"""

import caldav
import datetime
import random
import feedparser
import os
import sys

import caldav
import datetime
import random
import feedparser
import os
import sys

APPLE_EMAIL = os.environ.get("APPLE_EMAIL", "")
APPLE_APP_PASSWORD = os.environ.get("APPLE_APP_PASSWORD", "")
CALDAV_URL = "https://caldav.icloud.com"

# --- Compliment pool setup ---
# Option A: Inline pool (simple, self-contained)
# COMPLIMENTS_POOL = [
#     "Your smile is literally the best part of my morning.",
#     "...",
# ]
#
# Option B: Import from external module (recommended for personalization)
# Create a file like `my_compliments.py` next to this script with:
#   COMPLIMENTS_POOL = ["...", "..."]
# Then uncomment the lines below:
# sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# from my_compliments import COMPLIMENTS_POOL

COMPLIMENTS_POOL = [
    "Replace with your own compliment pool or import from an external module.",
]

NEWS_FEEDS = [
    "https://feeds.bbci.co.uk/news/rss.xml",
    "https://feeds.bbci.co.uk/news/technology/rss.xml",
]


def get_today_events():
    if not APPLE_EMAIL or not APPLE_APP_PASSWORD:
        return "*Calendar not configured.*"
    try:
        client = caldav.DAVClient(
            url=CALDAV_URL,
            username=APPLE_EMAIL,
            password=APPLE_APP_PASSWORD,
        )
        principal = client.principal()
        calendars = principal.calendars()
        if not calendars:
            return "*No calendars found.*"

        today = datetime.date.today()
        tomorrow = today + datetime.timedelta(days=1)
        all_events = []

        for calendar in calendars:
            try:
                events = calendar.search(
                    start=today,
                    end=tomorrow,
                    event=True,
                    expand=True,
                )
                for event in events:
                    vevent = event.vobject_instance.vevent
                    # Fix vobject summary wrapper
                    raw_summary = vevent.summary
                    if hasattr(raw_summary, 'value'):
                        summary = raw_summary.value
                    else:
                        summary = str(raw_summary)
                        if summary.startswith("<SUMMARY{") and summary.endswith(">"):
                            summary = summary[len("<SUMMARY{"):summary.rfind("}")]

                    dtstart = getattr(vevent, "dtstart", None)
                    time_str = "All day"
                    if dtstart:
                        st = dtstart.value
                        if isinstance(st, datetime.datetime):
                            time_str = st.strftime("%H:%M")
                    all_events.append(f"• {time_str}: {summary}")
            except Exception as e:
                print(f"Calendar error: {e}", file=sys.stderr)
                continue

        if not all_events:
            return "*No events scheduled for today.*"
        return "\n".join(sorted(all_events))
    except Exception as e:
        return f"*Couldn't fetch calendar: {e}*"


def get_news_articles():
    articles = []
    for feed_url in NEWS_FEEDS:
        try:
            feed = feedparser.parse(feed_url)
            for entry in feed.entries[:3]:
                title = entry.get("title", "").strip()
                link = entry.get("link", "").strip()
                if title and len(title) > 10 and link:
                    articles.append((title, link))
        except Exception:
            continue
    if not articles:
        return "*Couldn't fetch news today.*"
    selected = random.sample(articles, min(3, len(articles)))
    return "\n".join(f"• {title}\n  {link}" for title, link in selected)


def get_daily_compliment():
    return random.choice(COMPLIMENTS_POOL)


def main():
    events = get_today_events()
    news = get_news_articles()
    compliment = get_daily_compliment()
    today_str = datetime.date.today().strftime("%A, %B %d")

    message = f"""Good morning!

Today is {today_str}.

📅 Your day:
{events}

🌍 Today's headlines:
{news}

💝 For her:
{compliment}

Have a great day!"""

    print(message)


if __name__ == "__main__":
    main()
