#!/usr/bin/env python3
"""
Bookmark Channel Monitor for Discord
Monitors #bookmarks channel for new links and processes them automatically
"""

import re
import subprocess
import os

BOOKMARK_CHANNEL_ID = "1478094846165123102"
WORKSPACE_DIR = "/Users/neoclaw/.openclaw/workspace"

def extract_urls(text):
    """Extract URLs from text"""
    url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
    return re.findall(url_pattern, text)

def process_bookmark_url(url, author, content):
    """Process a bookmark URL using our bookmark processor"""
    try:
        # Run the bookmark processor
        cmd = [
            f"{WORKSPACE_DIR}/tools/bookmark-processor.sh",
            url,
            author,
            content[:100] if content else "no context"
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        
        if result.returncode == 0:
            return True, "Bookmark processed successfully"
        else:
            return False, f"Processing failed: {result.stderr}"
            
    except subprocess.TimeoutExpired:
        return False, "Processing timed out"
    except Exception as e:
        return False, f"Error: {str(e)}"

def send_bookmark_response(channel_id, url, success, message, filename=None):
    """Send response back to Discord channel"""
    if success:
        response = f"""📚 **Bookmark Saved**

🔗 **URL:** {url}
✅ **Status:** Successfully processed and archived
💾 **File:** `{filename}`

The content has been scraped, analyzed, and saved to markdown for future reference."""
    else:
        response = f"""❌ **Bookmark Error**

🔗 **URL:** {url}
❌ **Status:** Processing failed
🔍 **Reason:** {message}

Please try again or check the URL manually."""
    
    # Send via message tool (this would need to be implemented)
    print(f"Would send to channel {channel_id}: {response}")
    return response

def check_bookmarks_channel():
    """Check for new messages in bookmarks channel"""
    print(f"🔍 Monitoring bookmarks channel: {BOOKMARK_CHANNEL_ID}")
    
    # This would integrate with Discord message monitoring
    # For now, return a placeholder
    return []

def main():
    """Main monitoring function"""
    print("🚀 Bookmark Monitor Starting...")
    
    # Check for new messages in bookmarks channel
    new_messages = check_bookmarks_channel()
    
    for message in new_messages:
        author = message.get('author', 'unknown')
        content = message.get('content', '')
        
        # Extract URLs from message
        urls = extract_urls(content)
        
        for url in urls:
            print(f"📌 Found bookmark: {url} from {author}")
            
            success, result_message = process_bookmark_url(url, author, content)
            
            if success:
                # Find the most recent bookmark file
                bookmarks_dir = f"{WORKSPACE_DIR}/memory/bookmarks"
                if os.path.exists(bookmarks_dir):
                    files = sorted([f for f in os.listdir(bookmarks_dir) if f.startswith('bookmark-')], 
                                   key=lambda x: os.path.getctime(os.path.join(bookmarks_dir, x)), 
                                   reverse=True)
                    filename = files[0] if files else "unknown"
                else:
                    filename = "unknown"
                
                send_bookmark_response(BOOKMARK_CHANNEL_ID, url, True, result_message, filename)
            else:
                send_bookmark_response(BOOKMARK_CHANNEL_ID, url, False, result_message)
    
    print("✅ Bookmark monitoring complete")

if __name__ == "__main__":
    main()