#!/usr/bin/env python3
"""
Debug Campaign Script Generation

This script helps debug campaign creation issues by testing
the script generation process independently.
"""
import os
import sys
import json
from datetime import datetime

# Add app directory to path
sys.path.insert(0, '/home/ashraffarid2010/jadwaai.com')

def test_campaign_creation():
    """Test campaign creation for report 35."""
    print("=" * 80)
    print("CAMPAIGN CREATION DEBUG")
    print("=" * 80)

    try:
        # Simple database connection to get report data
        import psycopg2
        from psycopg2.extras import RealDictCursor

        conn = psycopg2.connect(
            host="127.0.0.1",
            port=5432,
            database="jadwa",
            user="postgres",
        )

        cursor = conn.cursor(cursor_factory=RealDictCursor)

        # Get report 35 data
        cursor.execute("""
            SELECT id, project_name, project_description, synthesis_result, language
            FROM reports
            WHERE id = 35
        """)

        report = cursor.fetchone()

        if not report:
            print("❌ Report 35 not found")
            return

        print(f"✅ Found Report 35:")
        print(f"   Project: {report['project_name']}")
        print(f"   Language: {report['language']}")
        print(f"   Has Synthesis: {'Yes' if report['synthesis_result'] else 'No'}")

        if not report['synthesis_result']:
            print("❌ Report synthesis_result is empty")
            return

        # Check if synthesis_result is valid JSON
        try:
            synthesis = json.loads(report['synthesis_result']) if isinstance(report['synthesis_result'], str) else report['synthesis_result']
            print(f"✅ Synthesis data is valid JSON")
            print(f"   Keys: {list(synthesis.keys())[:10]}...")
        except Exception as e:
            print(f"❌ Synthesis data is not valid JSON: {e}")
            return

        cursor.close()
        conn.close()

        print(f"\n🔍 Step 2: Testing script generation prompt...")

        # Try to import the video script prompt function
        try:
            from app.ai.prompts.video_script import get_video_script_prompt
            print("✅ Video script prompt module imported")
        except Exception as e:
            print(f"❌ Could not import video script prompt: {e}")
            return

        # Generate the prompt
        try:
            messages = get_video_script_prompt(
                synthesis,
                report['language'],
                duration_seconds=30,
                user_notes=None,
            )
            print(f"✅ Script prompt generated successfully")
            print(f"   Message count: {len(messages)}")

            # Show first message preview
            if messages and len(messages) > 0:
                first_msg = messages[0]
                content = first_msg.get('content', '') if isinstance(first_msg, dict) else str(first_msg)
                print(f"   First message preview: {content[:200]}...")

        except Exception as e:
            print(f"❌ Error generating script prompt: {e}")
            return

        print(f"\n🎯 RESULT:")
        print(f"The script generation process should work correctly.")
        print(f"If the UI still hangs, the issue might be:")
        print(f"1. Frontend timeout during form submission")
        print(f"2. Server timeout during AI processing")
        print(f"3. Network connection issues")
        print(f"4. Browser caching problems")

        print(f"\n💡 RECOMMENDATIONS:")
        print(f"1. Try clearing browser cache and cookies")
        print(f"2. Check browser console for JavaScript errors")
        print(f"3. Check network tab for failed requests")
        print(f"4. Try creating campaign with shorter notes")
        print(f"5. Check if AI API is working properly")

    except Exception as e:
        print(f"❌ Error during debug: {e}")
        import traceback
        traceback.print_exc()

    print("\n" + "=" * 80)

if __name__ == "__main__":
    test_campaign_creation()