#!/usr/bin/env python3
"""
harvey-status.py — Update Harvey's activity dashboard
Usage:
  python3 scripts/harvey-status.py working "Task name" "Detail"
  python3 scripts/harvey-status.py done "Task name" "Detail"
  python3 scripts/harvey-status.py queue "Task name" "Detail" [--urgent]
  python3 scripts/harvey-status.py clear-queue
  python3 scripts/harvey-status.py log "message" [done|error|info]
"""
import json, sys, datetime
from pathlib import Path

STATE_FILE = Path(__file__).parent.parent / 'www' / 'harvey-activity.json'

def now():
    from datetime import datetime, timezone
    import subprocess
    # Get local time in ET
    result = subprocess.run(['date', '+%H:%M EDT'], capture_output=True, text=True)
    return result.stdout.strip()

def load():
    if STATE_FILE.exists():
        return json.loads(STATE_FILE.read_text())
    return {"log": [], "queue": [], "updated": "", "current": {}, "last": {}}

def save(d):
    d['updated'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M EDT')
    STATE_FILE.write_text(json.dumps(d, indent=2))

def add_log(d, msg, typ='info'):
    d.setdefault('log', [])
    d['log'].append({"time": now(), "type": typ, "msg": msg})
    if len(d['log']) > 30:
        d['log'] = d['log'][-30:]

if __name__ == '__main__':
    args = sys.argv[1:]
    if not args:
        print(__doc__)
        sys.exit(0)

    d = load()
    cmd = args[0]

    if cmd == 'working':
        task = args[1] if len(args) > 1 else 'Working...'
        detail = args[2] if len(args) > 2 else ''
        d['current'] = {"task": task, "detail": detail, "since": now()}
        add_log(d, f'Started: {task}', 'info')

    elif cmd == 'done':
        task = args[1] if len(args) > 1 else d.get('current', {}).get('task', '—')
        detail = args[2] if len(args) > 2 else d.get('current', {}).get('detail', '')
        d['last'] = {"task": task, "detail": detail, "at": now()}
        d['current'] = {}
        add_log(d, task, 'done')

    elif cmd == 'queue':
        task = args[1] if len(args) > 1 else 'Queued task'
        detail = args[2] if len(args) > 2 else ''
        urgent = '--urgent' in args
        d.setdefault('queue', [])
        d['queue'].append({"task": task, "detail": detail, "urgent": urgent})

    elif cmd == 'clear-queue':
        d['queue'] = []

    elif cmd == 'dequeue':
        task = args[1] if len(args) > 1 else ''
        d['queue'] = [q for q in d.get('queue', []) if task.lower() not in q['task'].lower()]

    elif cmd == 'log':
        msg = args[1] if len(args) > 1 else ''
        typ = args[2] if len(args) > 2 else 'info'
        add_log(d, msg, typ)

    elif cmd == 'idle':
        d['current'] = {"task": "Idle", "detail": "Waiting for next task", "since": now()}

    save(d)
    print(f"Updated {STATE_FILE}")
