#!/usr/bin/env python3
"""
Test database connection and wireframe saving functionality
"""

import os
import psycopg2
from psycopg2.extras import RealDictCursor
from dotenv import load_dotenv
import json

def test_database_connection():
    """Test if we can connect to the database"""
    
    # Load environment variables
    load_dotenv()
    
    # Database connection details
    db_config = {
        'host': os.getenv('POSTGRES_HOST', 'localhost'),
        'database': os.getenv('POSTGRES_DB', 'dev_pipeline'),
        'user': os.getenv('POSTGRES_USER', 'pipeline_admin'),
        'password': os.getenv('POSTGRES_PASSWORD', 'secure_pipeline_2024'),
        'port': os.getenv('POSTGRES_PORT', '5433')
    }
    
    print("Testing database connection with config:")
    for key, value in db_config.items():
        if key == 'password':
            print(f"  {key}: {'*' * len(str(value))}")
        else:
            print(f"  {key}: {value}")
    
    try:
        # Test connection
        conn = psycopg2.connect(**db_config)
        print("✅ Database connection successful!")
        
        # Test if wireframes table exists
        with conn.cursor() as cur:
            cur.execute("""
                SELECT EXISTS (
                    SELECT FROM information_schema.tables 
                    WHERE table_schema = 'public' 
                    AND table_name = 'wireframes'
                );
            """)
            table_exists = cur.fetchone()[0]
            
            if table_exists:
                print("✅ Wireframes table exists!")
                
                # Test inserting a sample wireframe
                cur.execute("""
                    INSERT INTO wireframes (user_id, name, description, device_type, dimensions, metadata)
                    VALUES (%s, %s, %s, %s, %s, %s)
                    RETURNING id
                """, (
                    'testuser',
                    'Test Wireframe',
                    'Test wireframe for connection testing',
                    'desktop',
                    json.dumps({'width': 1440, 'height': 1024}),
                    json.dumps({'test': True, 'timestamp': '2024-01-01'})
                ))
                
                wireframe_id = cur.fetchone()[0]
                print(f"✅ Test wireframe inserted with ID: {wireframe_id}")
                
                # Clean up test data
                cur.execute("DELETE FROM wireframes WHERE id = %s", (wireframe_id,))
                print("✅ Test wireframe cleaned up")
                
            else:
                print("❌ Wireframes table does not exist!")
                print("Please run the database setup script first:")
                print("  python setup_database.py")
        
        conn.close()
        return True
        
    except Exception as e:
        print(f"❌ Database connection failed: {e}")
        return False

def test_api_endpoint():
    """Test if the API endpoint is accessible"""
    import requests
    
    try:
        response = requests.get('http://localhost:5000/api/health')
        if response.status_code == 200:
            print("✅ API endpoint is accessible!")
            print(f"Response: {response.json()}")
            return True
        else:
            print(f"❌ API endpoint returned status: {response.status_code}")
            return False
    except requests.exceptions.ConnectionError:
        print("❌ Cannot connect to API endpoint. Is the backend running?")
        print("Start the backend with: python app.py")
        return False
    except Exception as e:
        print(f"❌ API test failed: {e}")
        return False

if __name__ == "__main__":
    print("Testing Tech4biz Wireframe Generator...")
    print("=" * 50)
    
    # Test database connection
    db_ok = test_database_connection()
    print()
    
    # Test API endpoint
    api_ok = test_api_endpoint()
    print()
    
    if db_ok and api_ok:
        print("🎉 All tests passed! The system is ready to use.")
    else:
        print("❌ Some tests failed. Please fix the issues above.")
        
        if not db_ok:
            print("\nTo fix database issues:")
            print("1. Make sure PostgreSQL is running")
            print("2. Check your environment variables")
            print("3. Run: python setup_database.py")
            
        if not api_ok:
            print("\nTo fix API issues:")
            print("1. Start the backend: python app.py")
            print("2. Make sure it's running on port 5000")
