#!/usr/bin/env python3
"""
Main workflow orchestrator for Research to Presentation
Coordinates the complete pipeline from Notion to final presentation
"""

import json
import argparse
import subprocess
import sys
from pathlib import Path
from datetime import datetime

def run_workflow(notion_url, output_format='pptx', brand_config=None):
    """
    Execute the complete research to presentation workflow
    
    Args:
        notion_url: URL of Notion page or database
        output_format: 'pptx' or 'figma'  
        brand_config: Path to brand configuration JSON
    """
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    work_dir = Path(f"/tmp/r2p_{timestamp}")
    work_dir.mkdir(parents=True, exist_ok=True)
    
    print("🚀 Starting Research to Presentation Workflow")
    print(f"📍 Source: {notion_url}")
    print(f"📄 Output Format: {output_format}")
    print("-" * 50)
    
    try:
        # Step 1: Extract Notion content
        print("\n📚 Step 1: Extracting Notion research...")
        research_file = work_dir / "research.json"
        subprocess.run([
            sys.executable, "scripts/extract_notion.py",
            notion_url,
            "--output", str(research_file)
        ], check=True)
        print(f"✅ Research extracted to {research_file}")
        
        # Step 2: Synthesize content
        print("\n🔍 Step 2: Synthesizing content and extracting topics...")
        synthesis_file = work_dir / "synthesis.json"
        subprocess.run([
            sys.executable, "scripts/synthesize_content.py",
            str(research_file),
            "--output", str(synthesis_file)
        ], check=True)
        print(f"✅ Synthesis completed: {synthesis_file}")
        
        # Step 3: Generate presentation
        print(f"\n🎨 Step 3: Generating {output_format.upper()} presentation...")
        
        if output_format == 'pptx':
            output_file = f"presentation_{timestamp}.pptx"
            subprocess.run([
                "node", "scripts/generate_pptx.js",
                str(synthesis_file),
                output_file
            ], check=True)
            print(f"✅ PowerPoint created: {output_file}")
            
        elif output_format == 'figma':
            output_file = f"figma_slides_{timestamp}.json"
            subprocess.run([
                "node", "scripts/export_to_figma.js",
                str(synthesis_file),
                "--output", output_file
            ], check=True)
            print(f"✅ Figma slides exported: {output_file}")
        
        # Step 4: Apply branding (if config provided)
        if brand_config and output_format == 'pptx':
            print("\n🎨 Step 4: Applying brand styles...")
            subprocess.run([
                sys.executable, "scripts/apply_brand.py",
                output_file,
                "--config", brand_config
            ], check=True)
            print("✅ Brand styling applied")
        
        print("\n" + "=" * 50)
        print(f"🎉 Workflow completed successfully!")
        print(f"📁 Output: {output_file}")
        print(f"🗂️  Work files: {work_dir}")
        
        return output_file
        
    except subprocess.CalledProcessError as e:
        print(f"\n❌ Error in workflow: {e}")
        print(f"💡 Check work directory for debugging: {work_dir}")
        raise
    except Exception as e:
        print(f"\n❌ Unexpected error: {e}")
        raise

def main():
    parser = argparse.ArgumentParser(
        description="Transform Notion research into presentations"
    )
    parser.add_argument(
        "--notion-url",
        required=True,
        help="URL of Notion page or database"
    )
    parser.add_argument(
        "--output-format",
        choices=['pptx', 'figma'],
        default='pptx',
        help="Output format (default: pptx)"
    )
    parser.add_argument(
        "--brand-config",
        help="Path to brand configuration JSON"
    )
    parser.add_argument(
        "--preview",
        action='store_true',
        help="Generate HTML preview only"
    )
    
    args = parser.parse_args()
    
    if args.preview:
        print("🔍 Preview mode - generating HTML only")
        # Preview implementation here
    else:
        run_workflow(
            args.notion_url,
            args.output_format,
            args.brand_config
        )

if __name__ == "__main__":
    main()
