#!/usr/bin/env python3
"""
ClickUp Tasks Due Today — Daily notification script
Runs at 7 AM Pacific weekdays
- Team members get email with tasks due today + Monday Meeting Action Items
- Dustin gets Telegram message instead
"""

import requests, base64, sys
from datetime import datetime, timedelta
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

# --- Config ---
CLICKUP_API_KEY = "pk_82028520_WEWGZA7A2CRIZNH5QDVE4ZN9NIEA2YAB"
TEAM_ID = "9009180266"
MEETING_MINUTES_LIST = "901325894190"
GMAIL_TOKEN = "/Users/tonyclaw/.config/gmail/token.json"
SIGNATURE_PATH = "/Users/tonyclaw/.openclaw/workspace/assets/boules-signature.jpg"

TEAM = [
    {"name": "Melissa",  "first": "Melissa",  "id": 82117811, "email": "melissa@boulesconsulting.org"},
    {"name": "Marianne", "first": "Marianne", "id": 78200642, "email": "marianne@boulesconsulting.org"},
    {"name": "Carolina", "first": "Carolina", "id": 82174011, "email": "carolina@boulesconsulting.org"},
    {"name": "Lillian",  "first": "Lillian",  "id": 82033824, "email": "lillian@boulesconsulting.org"},
]
DUSTIN_ID = 82028520

headers = {"Authorization": CLICKUP_API_KEY}

def get_tasks_due_today(user_id):
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    start_ms = int(today.timestamp() * 1000)
    end_ms = int((today + timedelta(days=1) - timedelta(seconds=1)).timestamp() * 1000)
    r = requests.get(
        f"https://api.clickup.com/api/v2/team/{TEAM_ID}/task",
        headers=headers,
        params={
            "assignees[]": user_id,
            "due_date_gt": start_ms - 1,
            "due_date_lt": end_ms + 1,
            "include_closed": False,
            "subtasks": True,
            "page": 0
        }
    )
    tasks = r.json().get('tasks', [])
    # Filter out completed/closed/done tasks
    return [t for t in tasks if t.get('status', {}).get('status', '').lower() not in ['complete', 'closed', 'done']]

def get_past_due_tasks(user_id):
    """Get tasks assigned to user with due dates BEFORE today (not including today).
    Only includes tasks from Client (90130152010) and Admin (90131501526) spaces."""
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    end_ms = int(today.timestamp() * 1000)  # Tasks due before today
    ALLOWED_SPACES = ['90130152010', '90131501526']  # Client and Admin spaces only
    
    r = requests.get(
        f"https://api.clickup.com/api/v2/team/{TEAM_ID}/task",
        headers=headers,
        params={
            "assignees[]": user_id,
            "due_date_lt": end_ms,
            "include_closed": False,
            "subtasks": True,
            "page": 0
        }
    )
    tasks = r.json().get('tasks', [])
    # Filter by allowed spaces
    tasks = [t for t in tasks if str(t.get('space', {}).get('id', '')) in ALLOWED_SPACES]
    # Filter out completed/closed/done tasks
    tasks = [t for t in tasks if t.get('status', {}).get('status', '').lower() not in ['complete', 'closed', 'done']]
    # Add formatted due date to each task
    for t in tasks:
        if t.get('due_date'):
            due_ts = int(t['due_date']) / 1000  # Convert milliseconds to seconds
            due_dt = datetime.fromtimestamp(due_ts)
            t['due_date_formatted'] = due_dt.strftime("%b %-d, %Y").replace(' 0', ' ')
    return tasks

def get_action_items(user_id):
    """Get open 'to do' subtasks from meeting minutes list assigned to user."""
    r = requests.get(
        f"https://api.clickup.com/api/v2/list/{MEETING_MINUTES_LIST}/task",
        headers=headers,
        params={"include_closed": "true", "subtasks": "true", "page": 0}
    )
    all_tasks = r.json().get('tasks', [])
    return [
        t for t in all_tasks
        if t.get('parent')
        and t.get('status', {}).get('status', '').lower() == 'to do'
        and user_id in [a.get('id') for a in t.get('assignees', [])]
    ]

MEETING_MINUTES_TASK_ID = None  # Set at runtime if available

def send_email(person, due_tasks, past_due_tasks, action_items, gmail_service, sig_data):
    today_str = datetime.now().strftime("%b %-d")

    # Meeting minutes link at the top (if available)
    meeting_minutes_html = ""
    if MEETING_MINUTES_TASK_ID:
        mm_url = f"https://app.clickup.com/t/{MEETING_MINUTES_TASK_ID}"
        mm_date = datetime.now().strftime("%b %-d, %Y")
        meeting_minutes_html = f"""<p><strong>Today's Weekly Meeting Minutes:</strong><br>
<a href="{mm_url}">{mm_date} Weekly Team Meeting Minutes</a></p>
<hr style="border:none;border-top:1px solid #e5e7eb;margin:12px 0;">
"""

    # Past due tasks section (at the TOP)
    past_due_html = ""
    if past_due_tasks:
        past_due_html = '<h2 style="color:#dc2626;">⚠️ Past Due Tasks</h2>\n<ul>\n'
        for t in past_due_tasks:
            url = t.get('url', f"https://app.clickup.com/t/{t['id']}")
            due_date = t.get('due_date_formatted', 'Unknown date')
            past_due_html += f'  <li><a href="{url}">{t["name"]}</a> — was due {due_date}</li>\n'
        past_due_html += '</ul>\n<br>\n'
    
    # Tasks due today section
    if due_tasks:
        tasks_html = f"<p>Here are your tasks due <strong>today, {today_str}</strong>:</p>\n"
        for t in due_tasks:
            url = t.get('url', f"https://app.clickup.com/t/{t['id']}")
            space = t.get('space', {}).get('name', '')
            folder = t.get('folder', {}).get('name', '')
            loc = f"{space} › {folder}" if folder and folder != 'hidden' else space
            tasks_html += f'  • <a href="{url}">{t["name"]}</a> <span style="color:#888">({loc})</span><br>\n'
    else:
        tasks_html = f"<p>No tasks due today, {today_str}. Clear day!</p>\n"

    # Action items section
    action_html = ""
    if action_items:
        action_html = "<p><strong>Monday Meeting Action Items:</strong></p>\n"
        for t in action_items:
            url = t.get('url', f"https://app.clickup.com/t/{t['id']}")
            action_html += f'  • <a href="{url}">{t["name"]}</a><br>\n'

    html_body = f"""<p>Good morning {person['first']},</p>
{meeting_minutes_html}
{past_due_html}
{tasks_html}
<br>
{action_html}
<br>
<img src="cid:boules_signature" style="max-width:400px;">"""

    msg = MIMEMultipart('related')
    msg['To'] = person['email']
    msg['From'] = 'ohmandd@gmail.com'
    msg['Subject'] = f'ClickUp — Tasks Due Today ({today_str})'

    alt = MIMEMultipart('alternative')
    alt.attach(MIMEText(html_body, 'html'))
    msg.attach(alt)

    img = MIMEImage(sig_data, _subtype='jpeg')
    img.add_header('Content-ID', '<boules_signature>')
    img.add_header('Content-Disposition', 'inline', filename='signature.jpg')
    msg.attach(img)

    raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()

    # Draft mode — change to .send() when ready to auto-send
    draft = gmail_service.users().drafts().create(
        userId='me', body={'message': {'raw': raw}}
    ).execute()
    return draft['id']

def notify_dustin_telegram(due_tasks):
    """Print a message for Tony to forward to Dustin via Telegram."""
    today_str = datetime.now().strftime("%b %-d")
    if not due_tasks:
        print("DUSTIN_NOTIF: No tasks due today for you in ClickUp.")
        return
    lines = [f"📋 You have {len(due_tasks)} task(s) due today in ClickUp ({today_str}):"]
    for t in due_tasks:
        url = t.get('url', f"https://app.clickup.com/t/{t['id']}")
        lines.append(f"• {t['name']} — {url}")
    print("DUSTIN_NOTIF: " + "\n".join(lines))

def main():
    creds = Credentials.from_authorized_user_file(GMAIL_TOKEN)
    gmail = build('gmail', 'v1', credentials=creds)

    with open(SIGNATURE_PATH, 'rb') as f:
        sig_data = f.read()

    results = []

    # Team members — email
    for person in TEAM:
        due_tasks = get_tasks_due_today(person['id'])
        past_due_tasks = get_past_due_tasks(person['id'])
        action_items = get_action_items(person['id'])

        if not due_tasks and not past_due_tasks and not action_items:
            print(f"SKIP {person['name']} — nothing due, no past due, no action items")
            continue

        draft_id = send_email(person, due_tasks, past_due_tasks, action_items, gmail, sig_data)
        print(f"DRAFT {person['name']}: {len(past_due_tasks)} past due, {len(due_tasks)} due today, {len(action_items)} action items — draft {draft_id}")
        results.append(person['name'])

    # Dustin — Telegram only
    dustin_tasks = get_tasks_due_today(DUSTIN_ID)
    notify_dustin_telegram(dustin_tasks)

    print(f"\nDone. Drafts created for: {', '.join(results) if results else 'none'}")

if __name__ == '__main__':
    main()

# TONY-APPROVED: 2026-03-01 | sha:f30fa5e9
