#!/usr/bin/env python3
"""
Read Notion meeting transcription content via browser automation.
Runs on Mac node to access content blocked by API.

Usage: python3 read_meeting.py <page_id> [--json]
"""

import sys
import json
import time
import subprocess
from pathlib import Path

def read_meeting_applescript(page_id: str) -> dict:
    """Use AppleScript to read Notion page content from Chrome."""
    
    notion_url = f"https://www.notion.so/{page_id.replace('-', '')}"
    
    # AppleScript to open URL and extract page content
    script = f'''
    tell application "Google Chrome"
        activate
        
        -- Find or create tab with Notion
        set found to false
        set targetTab to missing value
        
        repeat with w in windows
            repeat with t in tabs of w
                if URL of t starts with "https://www.notion.so/" then
                    set URL of t to "{notion_url}"
                    set targetTab to t
                    set found to true
                    exit repeat
                end if
            end repeat
            if found then exit repeat
        end repeat
        
        if not found then
            tell front window
                set targetTab to make new tab with properties {{URL:"{notion_url}"}}
            end tell
        end if
        
        -- Wait for page to load
        delay 3
        
        -- Get page content via JavaScript
        tell targetTab
            set pageContent to execute javascript "
                (function() {{
                    // Find the main content area
                    const content = document.querySelector('.notion-page-content');
                    if (!content) return JSON.stringify({{error: 'No content found'}});
                    
                    // Extract text from all blocks
                    const blocks = content.querySelectorAll('[data-block-id]');
                    const texts = [];
                    
                    blocks.forEach(block => {{
                        const text = block.innerText.trim();
                        if (text) texts.push(text);
                    }});
                    
                    // Look for AI Summary section
                    const summaryMatch = document.body.innerText.match(/AI Summary[\\s\\S]*?(?=Action Items|Transcript|$)/i);
                    const actionMatch = document.body.innerText.match(/Action Items[\\s\\S]*?(?=Transcript|$)/i);
                    
                    return JSON.stringify({{
                        title: document.title,
                        url: window.location.href,
                        fullText: texts.join('\\n'),
                        summary: summaryMatch ? summaryMatch[0] : null,
                        actionItems: actionMatch ? actionMatch[0] : null
                    }});
                }})()
            "
            return pageContent
        end tell
    end tell
    '''
    
    try:
        result = subprocess.run(
            ['osascript', '-e', script],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if result.returncode != 0:
            return {"error": result.stderr, "returncode": result.returncode}
        
        # Parse the JSON result
        try:
            return json.loads(result.stdout.strip())
        except json.JSONDecodeError:
            return {"raw": result.stdout, "error": "Failed to parse JSON"}
            
    except subprocess.TimeoutExpired:
        return {"error": "Script timed out"}
    except Exception as e:
        return {"error": str(e)}


def read_meeting_playwright(page_id: str) -> dict:
    """Use Playwright to read Notion page content."""
    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        return {"error": "Playwright not installed. Run: pip install playwright && playwright install"}
    
    notion_url = f"https://www.notion.so/{page_id.replace('-', '')}"
    
    try:
        with sync_playwright() as p:
            # Use existing Chrome profile for auth
            browser = p.chromium.launch_persistent_context(
                user_data_dir=Path.home() / ".openclaw" / "browser" / "openclaw" / "user-data",
                headless=False,
                channel="chrome"
            )
            
            page = browser.pages[0] if browser.pages else browser.new_page()
            page.goto(notion_url)
            page.wait_for_load_state("networkidle", timeout=15000)
            
            # Wait for content to render
            time.sleep(2)
            
            # Extract content
            content = page.evaluate('''
                () => {
                    const body = document.body.innerText;
                    
                    // Look for AI Summary section
                    const summaryMatch = body.match(/AI Summary[\\s\\S]*?(?=Action Items|Transcript|Notes|$)/i);
                    const actionMatch = body.match(/Action Items[\\s\\S]*?(?=Transcript|Notes|$)/i);
                    const transcriptMatch = body.match(/Transcript[\\s\\S]*/i);
                    
                    return {
                        title: document.title,
                        url: window.location.href,
                        summary: summaryMatch ? summaryMatch[0].trim() : null,
                        actionItems: actionMatch ? actionMatch[0].trim() : null,
                        transcript: transcriptMatch ? transcriptMatch[0].substring(0, 5000).trim() : null
                    };
                }
            ''')
            
            browser.close()
            return content
            
    except Exception as e:
        return {"error": str(e)}


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 read_meeting.py <page_id> [--applescript|--playwright]")
        sys.exit(1)
    
    page_id = sys.argv[1]
    method = sys.argv[2] if len(sys.argv) > 2 else "--applescript"
    
    if method == "--playwright":
        result = read_meeting_playwright(page_id)
    else:
        result = read_meeting_applescript(page_id)
    
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
