#!/usr/bin/env python3
import json
import os
import re
import subprocess
from datetime import datetime
from pathlib import Path
import requests

WORKSPACE = Path('/Users/ahmad/.openclaw/workspace')
OUT = WORKSPACE / 'knowledge_base' / 'email_triage_daily.md'
ACCOUNT = 'ahmad@bigalc.com'
CLICKUP_CRED = WORKSPACE / 'clickup_credentials.md'
FOLLOWUP_LIST_ID = '901613526439'  # Meetings & Follow-ups
BASE = 'https://api.clickup.com/api/v2'


def run(cmd):
    p = subprocess.run(cmd, capture_output=True, text=True)
    if p.returncode != 0:
        raise RuntimeError(p.stderr.strip() or 'command failed')
    return p.stdout


def get_clickup_token():
    txt = CLICKUP_CRED.read_text(encoding='utf-8')
    m = re.search(r'\bpk_[A-Za-z0-9_]+\b', txt)
    return m.group(0) if m else None


def clickup_get_tasks(token):
    r = requests.get(f'{BASE}/list/{FOLLOWUP_LIST_ID}/task', headers={'Authorization': token}, params={'include_closed': 'true'}, timeout=30)
    r.raise_for_status()
    return r.json().get('tasks', [])


def clickup_create_task(token, name, description):
    payload = {'name': name, 'description': description, 'tags': ['email-ops', 'follow-up']}
    r = requests.post(f'{BASE}/list/{FOLLOWUP_LIST_ID}/task', headers={'Authorization': token, 'Content-Type': 'application/json'}, json=payload, timeout=30)
    r.raise_for_status()
    return r.json().get('id')


def classify(subject, sender):
    s = (subject or '').lower()
    f = (sender or '').lower()

    urgent_kw = ['urgent', 'asap', 'invoice due', 'payment', 'contract', 'proposal', 'follow up', 'follow-up', 'meeting', 'client']
    ignore_kw = ['unsubscribe', 'newsletter', 'sale', 'offer', 'invitation', 'masterclass', 'discount']

    if any(k in s for k in urgent_kw):
        return 'P1 urgent'
    if any(k in s for k in ignore_kw) or any(k in f for k in ['noreply', 'newsletter', 'rewards@', 'marketing']):
        return 'P4 ignore/newsletter'
    if any(k in s for k in ['re:', 'fwd:', 'question', 'review']):
        return 'P2 action'
    return 'P3 fyi'


def main():
    OUT.parent.mkdir(parents=True, exist_ok=True)

    raw = run(['gog', 'gmail', 'search', '--account', ACCOUNT, 'newer_than:1d', '--json'])
    data = json.loads(raw)
    threads = data.get('threads', []) if isinstance(data, dict) else []

    scored = []
    for t in threads[:80]:
        subject = t.get('subject', '')
        sender = t.get('from', '')
        date = t.get('date', '')
        tid = t.get('id', '')
        cls = classify(subject, sender)
        scored.append({'id': tid, 'subject': subject, 'from': sender, 'date': date, 'class': cls})

    p1 = [x for x in scored if x['class'] == 'P1 urgent']
    p2 = [x for x in scored if x['class'] == 'P2 action']
    p3 = [x for x in scored if x['class'] == 'P3 fyi']
    p4 = [x for x in scored if x['class'] == 'P4 ignore/newsletter']

    created = []
    token = get_clickup_token()
    if token:
        existing_names = {t.get('name', '').strip().lower() for t in clickup_get_tasks(token)}
        for item in (p1 + p2)[:20]:
            name = f"Email Follow-up: {item['subject'][:120]}"
            if name.lower() in existing_names:
                continue
            desc = f"From: {item['from']}\nDate: {item['date']}\nThread ID: {item['id']}\nPriority: {item['class']}\n\nAction: Review and respond."
            try:
                tid = clickup_create_task(token, name, desc)
                created.append((name, tid))
            except Exception:
                pass

    lines = []
    lines.append('# Email Ops v1 Daily Triage')
    lines.append(f'- Generated: {datetime.now().isoformat(timespec="seconds")}')
    lines.append('')
    lines.append('## Summary')
    lines.append(f'- Total threads scanned: {len(scored)}')
    lines.append(f'- P1 urgent: {len(p1)}')
    lines.append(f'- P2 action: {len(p2)}')
    lines.append(f'- P3 fyi: {len(p3)}')
    lines.append(f'- P4 ignore/newsletter: {len(p4)}')
    lines.append(f'- ClickUp follow-up tasks created: {len(created)}')
    lines.append('')

    def add_section(title, items, limit=10):
        lines.append(f'## {title}')
        if not items:
            lines.append('- None')
        else:
            for i in items[:limit]:
                lines.append(f"- [{i['date']}] {i['subject']} — {i['from']} (id: {i['id']})")
        lines.append('')

    add_section('P1 urgent', p1)
    add_section('P2 action', p2)
    add_section('P3 fyi', p3)

    lines.append('## Actions')
    if created:
        for n, tid in created[:20]:
            lines.append(f'- Created ClickUp task: {n} -> https://app.clickup.com/t/{tid}')
    else:
        lines.append('- No new ClickUp follow-up tasks created (none needed or already existed).')
    lines.append('')

    lines.append('## Risks / Gaps')
    lines.append('- Classification is heuristic; tune sender/domain allowlists for better precision.')
    lines.append('- No auto-reply sent yet; this version only triages and creates follow-up tasks.')
    lines.append('')

    lines.append('## Next Run Improvements')
    lines.append('- Add per-sender importance scoring and response draft generation for P1/P2.')
    lines.append('- Add explicit newsletter suppression list from historical behavior.')

    OUT.write_text('\n'.join(lines), encoding='utf-8')
    print(str(OUT))


if __name__ == '__main__':
    main()
