#!/usr/bin/env python3
"""
Debug OpenAI Analysis
"""

import os
import sys
sys.path.append('lib')

from openai_analyzer import OpenAILayoutAnalyzer
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

def test_openai_connection():
    """Test if OpenAI connection works"""
    
    print("🔍 Testing OpenAI Connection...")
    print(f"OpenAI API Key: {'***' + os.getenv('OPENAI_API_KEY', 'NOT_SET')[-4:] if os.getenv('OPENAI_API_KEY') else 'NOT_SET'}")
    
    try:
        analyzer = OpenAILayoutAnalyzer()
        print("✅ OpenAI analyzer initialized successfully")
        
        # Test with a simple text prompt (not image)
        import openai
        client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
        
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": "Say 'Hello from OpenAI API test'"}],
            max_tokens=20
        )
        
        print(f"✅ OpenAI API test successful: {response.choices[0].message.content}")
        return True
        
    except Exception as e:
        print(f"❌ OpenAI connection failed: {e}")
        return False

def test_with_screenshot():
    """Test analyzing a screenshot if available"""
    
    print("\n🖼️  Testing Screenshot Analysis...")
    
    # Look for any existing screenshots
    screenshots_dir = "screenshots"
    if os.path.exists(screenshots_dir):
        screenshots = [f for f in os.listdir(screenshots_dir) if f.endswith(('.png', '.jpg', '.jpeg'))]
        if screenshots:
            screenshot_path = os.path.join(screenshots_dir, screenshots[0])
            print(f"Found screenshot: {screenshot_path}")
            
            try:
                analyzer = OpenAILayoutAnalyzer()
                print("Calling analyze_screenshot...")
                asr = analyzer.analyze_screenshot(screenshot_path, "https://test.com")
                
                if asr:
                    print(f"✅ ASR Generated with {len(asr.get('template_structure', []))} sections")
                    print("\nTemplate Structure:")
                    for i, structure in enumerate(asr.get('template_structure', [])):
                        print(f"  {i+1}. {structure}")
                    
                    print(f"\nRaw Response Preview:")
                    raw = asr.get('raw_response', '')
                    print(raw[:500] + "..." if len(raw) > 500 else raw)
                else:
                    print("❌ No ASR generated")
                    
            except Exception as e:
                print(f"❌ Screenshot analysis failed: {e}")
                import traceback
                traceback.print_exc()
        else:
            print("No screenshots found in screenshots/ directory")
    else:
        print("No screenshots/ directory found")

if __name__ == "__main__":
    print("=== OpenAI Debug Test ===")
    
    if test_openai_connection():
        test_with_screenshot()
    else:
        print("Cannot test screenshot analysis - OpenAI connection failed") 