#!/usr/bin/env python3
"""Scan email + calendar across all connected Google accounts."""
import json, os
from datetime import datetime, timedelta, timezone
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

ACCOUNTS = [
    {'name': 'kitt@curiousendeavor.com', 'token': 'google-auth/token.json'},
    {'name': 'assafdagancos@gmail.com', 'token': 'google-auth/token-personal.json'},
]

LAST_CHECK_DIR = 'data/email-scan-state'

def get_creds(token_path):
    with open(token_path) as f:
        d = json.load(f)
    return Credentials(
        token=d.get('access_token'),
        refresh_token=d.get('refresh_token'),
        token_uri='https://oauth2.googleapis.com/token',
        client_id=d['client_id'],
        client_secret=d['client_secret'],
    )

def check_email(account):
    creds = get_creds(account['token'])
    svc = build('gmail', 'v1', credentials=creds)
    results = svc.users().messages().list(
        userId='me', maxResults=10, labelIds=['INBOX'], q='is:unread'
    ).execute()
    messages = results.get('messages', [])
    
    # Load seen IDs
    os.makedirs(LAST_CHECK_DIR, exist_ok=True)
    state_file = os.path.join(LAST_CHECK_DIR, account['name'].replace('@', '_at_').replace('.', '_') + '.txt')
    seen_ids = set()
    if os.path.exists(state_file):
        with open(state_file) as f:
            seen_ids = set(f.read().strip().split('\n'))
    
    new_msgs = []
    for m in messages:
        if m['id'] not in seen_ids:
            msg = svc.users().messages().get(
                userId='me', id=m['id'], format='metadata',
                metadataHeaders=['From', 'Subject', 'Date']
            ).execute()
            headers = {h['name']: h['value'] for h in msg['payload']['headers']}
            new_msgs.append({
                'id': m['id'],
                'from': headers.get('From', '?'),
                'subject': headers.get('Subject', '?'),
                'snippet': msg.get('snippet', '')[:200]
            })
    
    # Save seen IDs
    all_ids = list(seen_ids) + [m['id'] for m in new_msgs]
    with open(state_file, 'w') as f:
        f.write('\n'.join(all_ids[-200:]))
    
    return new_msgs

def check_calendar(account):
    creds = get_creds(account['token'])
    cal = build('calendar', 'v3', credentials=creds)
    now = datetime.now(timezone.utc)
    end = now + timedelta(hours=24)
    events = cal.events().list(
        calendarId='primary',
        timeMin=now.isoformat(),
        timeMax=end.isoformat(),
        maxResults=20,
        singleEvents=True,
        orderBy='startTime'
    ).execute().get('items', [])
    return events

def main():
    has_output = False
    
    # Email scan
    for account in ACCOUNTS:
        try:
            msgs = check_email(account)
            if msgs:
                has_output = True
                print(f"## 📬 {account['name']} — {len(msgs)} new")
                for m in msgs:
                    print(f"**{m['subject']}**")
                    print(f"From: {m['from']}")
                    if m['snippet']:
                        print(f"Preview: {m['snippet']}")
                    print()
        except Exception as e:
            print(f"⚠️ Email check failed for {account['name']}: {e}")
            has_output = True
    
    # Calendar scan (deduplicate events across accounts)
    all_events = []
    seen_summaries = set()
    for account in ACCOUNTS:
        try:
            events = check_calendar(account)
            for e in events:
                key = (e.get('summary', ''), e['start'].get('dateTime', e['start'].get('date')))
                if key not in seen_summaries:
                    seen_summaries.add(key)
                    all_events.append(e)
        except Exception as e:
            print(f"⚠️ Calendar check failed for {account['name']}: {e}")
            has_output = True
    
    if all_events:
        has_output = True
        print(f"## 📅 Calendar — next 24h")
        for e in sorted(all_events, key=lambda x: x['start'].get('dateTime', x['start'].get('date', ''))):
            start = e['start'].get('dateTime', e['start'].get('date'))
            summary = e.get('summary', '(No title)')
            location = e.get('location', '')
            attendees = e.get('attendees', [])
            names = [a.get('displayName', a.get('email', '?')) for a in attendees[:5]]
            
            line = f"**{summary}** — {start}"
            if location:
                line += f"\n  📍 {location}"
            if names:
                line += f"\n  👥 {', '.join(names)}"
            print(line)
            print()
    
    if not has_output:
        print("NO_NEWS")

if __name__ == '__main__':
    main()
