#!/usr/bin/env python3
"""Sync Trello boards to Harvey's memory. Run daily or on demand."""
import urllib.request, urllib.parse, json, os, sys
from datetime import datetime, timezone

API_KEY = open(os.path.expanduser('~/.openclaw/secrets/trello-api-key.txt')).read().strip()
TOKEN = open(os.path.expanduser('~/.openclaw/secrets/trello-token.txt')).read().strip()
BASE = 'https://api.trello.com/1'

BOARDS = {
    'NMC': '69b9c424ee331d28c6af7ede',
}

def api(path, **data):
    data['key'] = API_KEY
    data['token'] = TOKEN
    url = f"{BASE}{path}?" + urllib.parse.urlencode(data)
    return json.loads(urllib.request.urlopen(url).read())

def sync_boards():
    output = []
    output.append(f"# Trello Board Sync — {datetime.now().strftime('%Y-%m-%d %H:%M')}\n")

    for board_name, board_id in BOARDS.items():
        output.append(f"## {board_name} Board\n")
        
        # Get lists
        lists = api(f'/boards/{board_id}/lists')
        list_map = {l['id']: l['name'] for l in lists}
        
        # Get all cards
        cards = api(f'/boards/{board_id}/cards', fields='name,idList,due,dateLastActivity,closed')
        
        for lst in lists:
            list_cards = [c for c in cards if c['idList'] == lst['id'] and not c.get('closed')]
            if list_cards or 'Done' not in lst['name']:
                output.append(f"\n**{lst['name']}** ({len(list_cards)} cards)")
                for card in list_cards:
                    due = f" [due {card['due'][:10]}]" if card.get('due') else ''
                    output.append(f"  - {card['name']}{due}")
        
        output.append("")

    result = '\n'.join(output)
    print(result)
    
    # Save to memory
    sync_file = os.path.expanduser('~/.openclaw/workspace/memory/trello-state.md')
    with open(sync_file, 'w') as f:
        f.write(result)
    
    return result

if __name__ == '__main__':
    sync_boards()
