import os
import sys
import smtplib
import ssl
import json
import urllib.request
from email.mime.text import MIMEText
from datetime import datetime

# ------------------------------------------------------------------
# Configuration
# ------------------------------------------------------------------
SMTP_SERVER = "smtp.mail.me.com"
SMTP_PORT = 587
TO_ADDR = "sage.stockmans@pm.me"
FROM_ADDR = os.environ.get("APPLE_EMAIL", "").strip()
APPLE_ID_PASSWORD = os.environ.get("APPLE_ID_PASSWORD", "").strip()
APPLE_APP_PASSWORD = os.environ.get("APPLE_APP_PASSWORD", "").strip()

# Determine password to use: prefer app-specific password
PASSWORD = APPLE_APP_PASSWORD if APPLE_APP_PASSWORD else APPLE_ID_PASSWORD

# ------------------------------------------------------------------
# Validate credentials
# ------------------------------------------------------------------
if not FROM_ADDR:
    print("ERROR: APPLE_EMAIL environment variable is missing or empty.", file=sys.stderr)
    sys.exit(1)
if not PASSWORD:
    print("ERROR: Neither APPLE_APP_PASSWORD nor APPLE_ID_PASSWORD is set.", file=sys.stderr)
    sys.exit(1)

print(f"Sending from: {FROM_ADDR}")
print(f"Sending to:   {TO_ADDR}")

# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def fetch_json(url, timeout=20):
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "MorningBriefing/1.0"})
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except Exception as e:
        print(f"Warning: failed to fetch {url}: {e}", file=sys.stderr)
        return None

# ------------------------------------------------------------------
# 1. Weather for Brussels (Open-Meteo)
# ------------------------------------------------------------------
weather_summary = "Weather data currently unavailable."
weather_url = (
    "https://api.open-meteo.com/v1/forecast"
    "?latitude=50.85&longitude=4.35&current_weather=true"
)
weather_data = fetch_json(weather_url)
if weather_data and "current_weather" in weather_data:
    cw = weather_data["current_weather"]
    temp = cw.get("temperature", "?")
    wind = cw.get("windspeed", "?")
    wcode = cw.get("weathercode", 0)
    # WMO Weather interpretation codes (simplified)
    code_map = {
        0: "Clear sky",
        1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
        45: "Fog", 48: "Depositing rime fog",
        51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle",
        56: "Light freezing drizzle", 57: "Dense freezing drizzle",
        61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
        66: "Light freezing rain", 67: "Heavy freezing rain",
        71: "Slight snow fall", 73: "Moderate snow fall", 75: "Heavy snow fall",
        77: "Snow grains",
        80: "Slight rain showers", 81: "Moderate rain showers", 82: "Violent rain showers",
        85: "Slight snow showers", 86: "Heavy snow showers",
        95: "Thunderstorm", 96: "Thunderstorm with slight hail", 99: "Thunderstorm with heavy hail",
    }
    condition = code_map.get(wcode, f"Weather code {wcode}")
    weather_summary = (
        f"Current weather in Brussels: {condition}, {temp}°C, wind {wind} km/h."
    )

# ------------------------------------------------------------------
# 2. Tech news summary (Hacker News top stories)
# ------------------------------------------------------------------
tech_news = "Tech news summary currently unavailable."
hn_url = "https://hacker-news.firebaseio.com/v0/topstories.json"
hn_data = fetch_json(hn_url)
if hn_data and isinstance(hn_data, list):
    story_ids = hn_data[:5]
    stories = []
    for sid in story_ids:
        story_url = f"https://hacker-news.firebaseio.com/v0/item/{sid}.json"
        story = fetch_json(story_url)
        if story:
            title = story.get("title", "Untitled")
            url = story.get("url", "")
            if url:
                stories.append(f"- {title} ({url})")
            else:
                stories.append(f"- {title}")
    if stories:
        tech_news = "Top Hacker News stories:\n" + "\n".join(stories)

# ------------------------------------------------------------------
# 3. "For her" compliment for Caoil Heather Dezeure
# ------------------------------------------------------------------
compliment = (
    "For Caoil Heather Dezeure: "
    "Your kindness and presence make every day brighter."
    " Here's to you — may your morning be as lovely as you are."
)

# ------------------------------------------------------------------
# 4. Build email body
# ------------------------------------------------------------------
now_str = datetime.now().strftime("%A, %d %B %Y")
body = f"""Good morning,

Here's your morning briefing for {now_str}.

WEATHER
{weather_summary}

FOR HER
{compliment}

TECH NEWS
{tech_news}

Have a great day!
--
Morning Briefing Bot
"""

# ------------------------------------------------------------------
# 5. Send email via iCloud SMTP (STARTTLS)
# ------------------------------------------------------------------
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = "Morning Briefing"
msg["From"] = FROM_ADDR
msg["To"] = TO_ADDR

try:
    context = ssl.create_default_context()
    server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    server.starttls(context=context)
    server.login(FROM_ADDR, PASSWORD)
    server.sendmail(FROM_ADDR, [TO_ADDR], msg.as_string())
    server.quit()
    print("SUCCESS: Morning Briefing email sent successfully.")
except smtplib.SMTPAuthenticationError as e:
    print(f"FAILURE: SMTP authentication failed: {e}", file=sys.stderr)
    sys.exit(1)
except Exception as e:
    print(f"FAILURE: Could not send email: {e}", file=sys.stderr)
    sys.exit(1)
