#!/usr/bin/env python3
"""
Migrate Discord messages from source threads to destination channels.
Reads messages via Discord API, formats them, and sends to destination.
"""
import json
import sys
import os
import subprocess
import time
from datetime import datetime

def read_messages(channel_id, limit=100, before=None):
    """Read messages from a channel using openclaw CLI"""
    cmd = f'openclaw message read --target {channel_id} --limit {limit}'
    if before:
        cmd += f' --before {before}'
    cmd += ' --format json'
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    try:
        data = json.loads(result.stdout)
        if data.get('ok'):
            return data.get('messages', [])
    except:
        pass
    return []

def send_message(channel_id, message):
    """Send a message to a channel"""
    # Write message to temp file to handle special chars
    tmp = '/tmp/discord_msg.txt'
    with open(tmp, 'w') as f:
        f.write(message)
    
    cmd = f'openclaw message send --target {channel_id} --message-file {tmp}'
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    time.sleep(0.5)  # Rate limit
    return result.returncode == 0

def format_message(msg):
    """Format a message for reposting"""
    author = msg.get('author', {})
    display_name = author.get('global_name') or author.get('username', 'Unknown')
    
    timestamp = msg.get('timestamp', '')
    try:
        dt = datetime.fromisoformat(timestamp.replace('+00:00', '+00:00'))
        time_str = dt.strftime('%Y-%m-%d %H:%M')
    except:
        time_str = timestamp[:16]
    
    content = msg.get('content', '')
    
    # Build formatted message
    parts = [f"**[{display_name}] — [{time_str} UTC]**"]
    if content:
        parts.append(content)
    
    # Add attachments
    for att in msg.get('attachments', []):
        url = att.get('url', '')
        name = att.get('filename', 'attachment')
        parts.append(f"📎 Attachment: {name} — {url}")
    
    return '\n'.join(parts)

def get_all_messages(channel_id):
    """Get all messages from a channel, paginating as needed"""
    all_msgs = []
    before = None
    while True:
        msgs = read_messages(channel_id, 100, before)
        if not msgs:
            break
        all_msgs.extend(msgs)
        if len(msgs) < 100:
            break
        before = msgs[-1]['id']  # Messages come newest-first
    return all_msgs

def migrate(source_id, dest_id, name):
    """Migrate all messages from source to destination"""
    print(f"Reading messages from {source_id} ({name})...")
    messages = get_all_messages(source_id)
    
    # Filter out system messages (type 7=guild member join, 18=channel follow, 21=thread starter)
    user_msgs = [m for m in messages if m.get('type', 0) not in (7, 18, 21)]
    
    # Reverse to oldest-first
    user_msgs.reverse()
    
    print(f"Found {len(user_msgs)} messages to migrate")
    
    sent = 0
    failed = 0
    for i, msg in enumerate(user_msgs):
        formatted = format_message(msg)
        if len(formatted) > 1900:
            # Split long messages
            chunks = [formatted[j:j+1900] for j in range(0, len(formatted), 1900)]
            for chunk in chunks:
                if send_message(dest_id, chunk):
                    sent += 1
                else:
                    failed += 1
        else:
            if send_message(dest_id, formatted):
                sent += 1
            else:
                failed += 1
        
        if (i + 1) % 10 == 0:
            print(f"  Progress: {i+1}/{len(user_msgs)}")
    
    print(f"Complete: {sent} sent, {failed} failed")
    return sent, failed

if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("Usage: migrate_thread.py SOURCE_ID DEST_ID NAME")
        sys.exit(1)
    
    source_id = sys.argv[1]
    dest_id = sys.argv[2]
    name = sys.argv[3]
    
    sent, failed = migrate(source_id, dest_id, name)
    print(json.dumps({"sent": sent, "failed": failed, "name": name}))
