#!/usr/bin/env python3
"""
Diagnose frontend issues:
1. Check if backend API is running and accessible
2. Check database connection
3. Test search endpoint
"""

import os
import sys
import requests
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from backend.db.session import get_database_url, engine
from sqlalchemy import text

def check_backend_api():
    """Check if backend API is running."""
    print("=" * 80)
    print("BACKEND API CHECK")
    print("=" * 80)
    
    try:
        # Check if docs endpoint is accessible
        response = requests.get("http://127.0.0.1:8000/docs", timeout=5)
        if response.status_code == 200:
            print("✅ Backend API is running (docs accessible)")
        else:
            print(f"⚠️  Backend API returned status {response.status_code}")
    except requests.exceptions.ConnectionError:
        print("❌ Backend API is NOT running or not accessible")
        print("   Start it with: cd backend && uvicorn app:app --reload")
        return False
    except Exception as e:
        print(f"❌ Error checking backend API: {e}")
        return False
    
    # Check search endpoint (requires auth)
    try:
        response = requests.get(
            "http://127.0.0.1:8000/api/v1/photos",
            params={"search_type": "processed", "page": 1, "page_size": 1},
            timeout=5
        )
        if response.status_code == 200:
            print("✅ Search endpoint is accessible (no auth required for this query)")
        elif response.status_code == 401:
            print("⚠️  Search endpoint requires authentication")
            print("   User needs to log in through admin frontend")
        else:
            print(f"⚠️  Search endpoint returned status {response.status_code}")
    except Exception as e:
        print(f"⚠️  Error checking search endpoint: {e}")
    
    return True

def check_database():
    """Check database connection and photo count."""
    print("\n" + "=" * 80)
    print("DATABASE CHECK")
    print("=" * 80)
    
    db_url = get_database_url()
    print(f"Database URL: {db_url.replace('://', '://****') if '://' in db_url else db_url}")
    
    try:
        with engine.connect() as conn:
            # Check photo count
            result = conn.execute(text("SELECT COUNT(*) FROM photos WHERE processed = 1"))
            count = result.scalar()
            print(f"✅ Database connection successful")
            print(f"   Processed photos: {count}")
            
            if count == 0:
                print("⚠️  No processed photos found in database")
                print("   This explains why viewer frontend shows 0 photos")
            else:
                print(f"   Database has {count} processed photos")
                
    except Exception as e:
        print(f"❌ Database connection error: {e}")
        return False
    
    return True

def check_viewer_frontend_config():
    """Check viewer frontend configuration."""
    print("\n" + "=" * 80)
    print("VIEWER FRONTEND CONFIGURATION")
    print("=" * 80)
    
    viewer_env = project_root / "viewer-frontend" / ".env"
    if not viewer_env.exists():
        print("❌ viewer-frontend/.env file not found")
        return False
    
    with open(viewer_env) as f:
        content = f.read()
        if "DATABASE_URL" in content:
            # Extract DATABASE_URL
            for line in content.split("\n"):
                if line.startswith("DATABASE_URL="):
                    db_url = line.split("=", 1)[1].strip().strip('"')
                    print(f"Viewer frontend DATABASE_URL: {db_url.replace('://', '://****') if '://' in db_url else db_url}")
                    
                    # Check if it matches actual database
                    actual_db = get_database_url()
                    if "postgresql" in db_url and "sqlite" in actual_db:
                        print("❌ MISMATCH: Viewer frontend configured for PostgreSQL")
                        print("   but actual database is SQLite")
                        print("\n   SOLUTION OPTIONS:")
                        print("   1. Change viewer-frontend/.env DATABASE_URL to SQLite:")
                        print(f'      DATABASE_URL="file:../data/punimtag.db"')
                        print("   2. Update Prisma schema to use SQLite provider")
                        print("   3. Migrate database to PostgreSQL")
                        return False
                    elif "sqlite" in db_url and "sqlite" in actual_db:
                        print("✅ Viewer frontend configured for SQLite (matches actual database)")
                    else:
                        print("⚠️  Database type mismatch or unclear")
        else:
            print("⚠️  DATABASE_URL not found in viewer-frontend/.env")
    
    return True

def main():
    print("\n🔍 DIAGNOSING FRONTEND ISSUES\n")
    
    backend_ok = check_backend_api()
    db_ok = check_database()
    viewer_config_ok = check_viewer_frontend_config()
    
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    
    if not backend_ok:
        print("❌ Backend API is not running - admin frontend search will fail")
    else:
        print("✅ Backend API is running")
    
    if not db_ok:
        print("❌ Database connection issue")
    else:
        print("✅ Database connection OK")
    
    if not viewer_config_ok:
        print("❌ Viewer frontend configuration issue - needs to be fixed")
    else:
        print("✅ Viewer frontend configuration OK")
    
    print("\n" + "=" * 80)

if __name__ == "__main__":
    main()

