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

WORKSPACE = Path('/Users/ahmad/.openclaw/workspace')
STATE = WORKSPACE / 'memory' / 'email_p1_state.json'
REPORT = WORKSPACE / 'knowledge_base' / 'email_p1_watcher_status.md'
ACCOUNTS = ['ahmad@bigalc.com']


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


def classify(subject: str, sender: str) -> bool:
    s = (subject or '').lower()
    f = (sender or '').lower()
    urgent_kw = ['urgent', 'asap', 'invoice', 'payment', 'contract', 'proposal', 'deadline', 'franchise tax', 'action required']
    if any(k in s for k in urgent_kw):
        return True
    if 'payments@' in f and ('reminder' in s or 'tax' in s):
        return True
    return False


def load_state():
    if not STATE.exists():
        return {'seenP1': []}
    try:
        return json.loads(STATE.read_text(encoding='utf-8'))
    except Exception:
        return {'seenP1': []}


def save_state(state):
    STATE.parent.mkdir(parents=True, exist_ok=True)
    STATE.write_text(json.dumps(state, indent=2), encoding='utf-8')


def main():
    state = load_state()
    seen = set(state.get('seenP1', []))

    p1_items = []
    errors = []

    for acc in ACCOUNTS:
        try:
            raw = run(['gog', 'gmail', 'search', '--account', acc, 'newer_than:2d', '--max', '120', '--json'])
            data = json.loads(raw)
            for t in data.get('threads', []):
                subj = t.get('subject', '')
                sender = t.get('from', '')
                if classify(subj, sender):
                    p1_items.append({
                        'id': t.get('id', ''),
                        'subject': subj,
                        'from': sender,
                        'date': t.get('date', ''),
                        'account': acc,
                    })
        except Exception as e:
            errors.append(f'{acc}: {e}')

    # detect newly-seen P1 items
    new_items = [x for x in p1_items if x['id'] and x['id'] not in seen]
    for x in p1_items:
        if x['id']:
            seen.add(x['id'])

    save_state({'seenP1': sorted(list(seen))[-1000:]})

    REPORT.parent.mkdir(parents=True, exist_ok=True)
    lines = [
        '# Email P1 Watcher Status',
        f'- Generated: {datetime.now().isoformat(timespec="seconds")}',
        f'- Accounts: {", ".join(ACCOUNTS)}',
        f'- P1 found this run: {len(p1_items)}',
        f'- New P1 this run: {len(new_items)}',
    ]
    if errors:
        lines.append(f'- Errors: {" | ".join(errors)}')
    lines.append('')
    lines.append('## New P1 Items')
    if new_items:
        for x in new_items:
            lines.append(f"- [{x['date']}] {x['subject']} — {x['from']} (thread {x['id']})")
    else:
        lines.append('- None')
    REPORT.write_text('\n'.join(lines), encoding='utf-8')

    if errors:
        print('WATCHER_PARTIAL_ERROR')
    if new_items:
        print('NEW_P1_DETECTED')
        for x in new_items[:5]:
            print(f"{x['subject']} | {x['from']} | {x['id']}")
    else:
        print('NO_NEW_P1')


if __name__ == '__main__':
    main()
