#!/usr/bin/env python3
"""
Browser automation for PowerPoint analysis using premium accounts.
"""

import sys
import time
import json
from pathlib import Path

def generate_browser_instructions(presentation_data):
    """Generate instructions for browser automation based on presentation data."""
    
    instructions = {
        "premium_accounts_available": [
            "ChatGPT Pro",
            "Gemini Pro", 
            "Perplexity Pro"
        ],
        "analysis_options": [],
        "step_by_step_guide": []
    }
    
    # Analysis options based on presentation content
    total_slides = presentation_data.get('total_slides', 0)
    word_count = presentation_data.get('word_count', 0)
    
    instructions["analysis_options"].append({
        "platform": "ChatGPT Pro",
        "url": "https://chat.openai.com",
        "actions": [
            "Upload PPTX file",
            "Ask for presentation improvement suggestions",
            "Request executive summary generation",
            "Ask for audience-specific talking points"
        ],
        "best_for": "Creative improvements, language enhancement, audience adaptation"
    })
    
    instructions["analysis_options"].append({
        "platform": "Gemini Pro",
        "url": "https://gemini.google.com",
        "actions": [
            "Upload PPTX or share Google Slides link",
            "Ask for data analysis of presentation content",
            "Request visual design suggestions",
            "Get competitor analysis integration"
        ],
        "best_for": "Data-driven insights, visual design, competitive analysis"
    })
    
    instructions["analysis_options"].append({
        "platform": "Perplexity Pro",
        "url": "https://www.perplexity.ai",
        "actions": [
            "Use for research to strengthen presentation content",
            "Find latest statistics and data points",
            "Research industry trends relevant to presentation",
            "Find supporting evidence for key points"
        ],
        "best_for": "Research, data validation, trend analysis"
    })
    
    # Step-by-step guide
    instructions["step_by_step_guide"] = [
        {
            "step": 1,
            "action": "Open browser with profile='chrome'",
            "command": "browser(action='open', profile='chrome', targetUrl='https://chat.openai.com')",
            "description": "Start with ChatGPT Pro for general improvements"
        },
        {
            "step": 2,
            "action": "Upload PPTX file",
            "command": "browser(action='act', request={'kind': 'upload', 'paths': ['/path/to/presentation.pptx']})",
            "description": "Upload your presentation file"
        },
        {
            "step": 3,
            "action": "Ask for analysis",
            "prompt": f"""Analyze this {total_slides}-slide presentation and provide:
1. Executive summary
2. Key strengths and weaknesses
3. Suggestions for improvement
4. Audience-specific talking points
5. Visual design recommendations""",
            "description": "Comprehensive presentation analysis"
        },
        {
            "step": 4,
            "action": "Switch to Gemini for visual analysis",
            "command": "browser(action='open', profile='chrome', targetUrl='https://gemini.google.com')",
            "description": "Get visual design suggestions"
        },
        {
            "step": 5,
            "action": "Use Perplexity for research",
            "command": "browser(action='open', profile='chrome', targetUrl='https://www.perplexity.ai')",
            "description": "Strengthen content with research"
        }
    ]
    
    # Custom recommendations based on presentation metrics
    recommendations = []
    
    if total_slides > 20:
        recommendations.append("Presentation is lengthy. Consider creating a shorter executive version.")
    
    if word_count > 2000:
        recommendations.append("Text-heavy presentation. Consider adding more visuals.")
    
    if presentation_data.get('content_types', {}).get('Picture', 0) < total_slides * 0.5:
        recommendations.append("Could benefit from more images and visual elements.")
    
    instructions["custom_recommendations"] = recommendations
    
    return instructions

def main():
    if len(sys.argv) < 2:
        print("Usage: python3 browser_powerpoint_analysis.py <presentation.pptx> [analysis.json]")
        print("       python3 browser_powerpoint_analysis.py --from-json <analysis.json>")
        sys.exit(1)
    
    input_path = sys.argv[1]
    
    if input_path == "--from-json":
        # Load existing analysis
        if len(sys.argv) < 3:
            print("ERROR: Need JSON file path with --from-json")
            sys.exit(1)
        json_path = sys.argv[2]
        with open(json_path, 'r', encoding='utf-8') as f:
            presentation_data = json.load(f)
    else:
        # Extract data from PPTX
        pptx_path = input_path
        if not Path(pptx_path).exists():
            print(f"ERROR: File not found: {pptx_path}")
            sys.exit(1)
        
        # Try to extract basic data
        try:
            from pptx import Presentation
            prs = Presentation(pptx_path)
            presentation_data = {
                "filename": Path(pptx_path).name,
                "total_slides": len(prs.slides),
                "word_count": 0
            }
            
            # Simple word count
            for slide in prs.slides:
                for shape in slide.shapes:
                    if hasattr(shape, "text"):
                        presentation_data["word_count"] += len(shape.text.split())
            
        except ImportError:
            print("WARNING: python-pptx not installed. Using basic file info.")
            presentation_data = {
                "filename": Path(pptx_path).name,
                "total_slides": "Unknown (install python-pptx for analysis)",
                "word_count": "Unknown"
            }
        except Exception as e:
            print(f"WARNING: Could not analyze PPTX: {e}")
            presentation_data = {
                "filename": Path(pptx_path).name,
                "total_slides": "Unknown",
                "word_count": "Unknown"
            }
    
    # Generate browser instructions
    instructions = generate_browser_instructions(presentation_data)
    
    # Output
    output_path = sys.argv[2] if len(sys.argv) > 2 and sys.argv[1] != "--from-json" else None
    
    print("🖥️ BROWSER AUTOMATION GUIDE FOR PRESENTATION ANALYSIS")
    print("====================================================")
    print(f"Presentation: {presentation_data['filename']}")
    print(f"Slides: {presentation_data.get('total_slides', 'Unknown')}")
    print(f"Word count: {presentation_data.get('word_count', 'Unknown')}")
    print("")
    
    print("🎯 PREMIUM ACCOUNTS AVAILABLE:")
    for account in instructions["premium_accounts_available"]:
        print(f"  ✅ {account}")
    print("")
    
    print("📊 ANALYSIS OPTIONS:")
    for option in instructions["analysis_options"]:
        print(f"  🔹 {option['platform']}:")
        print(f"     URL: {option['url']}")
        print(f"     Best for: {option['best_for']}")
        for action in option['actions'][:2]:  # Show first 2 actions
            print(f"     • {action}")
        if len(option['actions']) > 2:
            print(f"     • ... and {len(option['actions']) - 2} more")
        print("")
    
    print("🔄 STEP-BY-STEP BROWSER AUTOMATION:")
    for step in instructions["step_by_step_guide"]:
        print(f"  {step['step']}. {step['action']}")
        print(f"     {step['description']}")
        if 'command' in step:
            print(f"     Command: {step['command']}")
        if 'prompt' in step:
            print(f"     Prompt: {step['prompt'][:80]}...")
        print("")
    
    if instructions.get('custom_recommendations'):
        print("💡 CUSTOM RECOMMENDATIONS:")
        for rec in instructions['custom_recommendations']:
            print(f"  • {rec}")
        print("")
    
    print("🚀 QUICK START COMMAND:")
    print("  browser(action='open', profile='chrome', targetUrl='https://chat.openai.com')")
    print("")
    print("📝 Note: Ensure Clawdbot Browser Relay Chrome extension is attached to the tab.")
    
    # Save instructions if output path provided
    if output_path:
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(instructions, f, indent=2, ensure_ascii=False)
        print(f"\n📄 Instructions saved to: {output_path}")

if __name__ == "__main__":
    main()