#!/usr/bin/env python3
"""Check all identified faces for pose information (web database)"""

import sys
import os

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.db.models import Face, Person, Photo
from backend.db.session import get_database_url

def check_identified_faces():
    """Check all identified faces for pose information"""
    db_url = get_database_url()
    print(f"Connecting to database: {db_url}")
    
    engine = create_engine(db_url)
    Session = sessionmaker(bind=engine)
    session = Session()
    
    try:
        # Get all identified faces with pose information
        faces = (
            session.query(Face, Person, Photo)
            .join(Person, Face.person_id == Person.id)
            .join(Photo, Face.photo_id == Photo.id)
            .filter(Face.person_id.isnot(None))
            .order_by(Person.id, Face.id)
            .all()
        )
        
        if not faces:
            print("No identified faces found.")
            return
        
        print(f"\n{'='*80}")
        print(f"Found {len(faces)} identified faces")
        print(f"{'='*80}\n")
        
        # Group by person
        by_person = {}
        for face, person, photo in faces:
            person_id = person.id
            if person_id not in by_person:
                by_person[person_id] = []
            by_person[person_id].append((face, person, photo))
        
        # Print summary
        print("SUMMARY BY PERSON:")
        print("-" * 80)
        for person_id, person_faces in by_person.items():
            person = person_faces[0][1]
            person_name = f"{person.first_name} {person.last_name}"
            pose_modes = [f[0].pose_mode for f in person_faces]
            frontal_count = sum(1 for p in pose_modes if p == 'frontal')
            profile_count = sum(1 for p in pose_modes if 'profile' in p)
            other_count = len(pose_modes) - frontal_count - profile_count
            
            print(f"\nPerson {person_id}: {person_name}")
            print(f"  Total faces: {len(person_faces)}")
            print(f"  Frontal: {frontal_count}")
            print(f"  Profile: {profile_count}")
            print(f"  Other: {other_count}")
            print(f"  Pose modes: {set(pose_modes)}")
        
        # Print detailed information
        print(f"\n{'='*80}")
        print("DETAILED FACE INFORMATION:")
        print(f"{'='*80}\n")
        
        for face, person, photo in faces:
            person_name = f"{person.first_name} {person.last_name}"
            print(f"Face ID: {face.id}")
            print(f"  Person: {person_name} (ID: {face.person_id})")
            print(f"  Photo: {photo.filename}")
            print(f"  Pose Mode: {face.pose_mode}")
            print(f"  Yaw: {face.yaw_angle:.2f}°" if face.yaw_angle is not None else "  Yaw: None")
            print(f"  Pitch: {face.pitch_angle:.2f}°" if face.pitch_angle is not None else "  Pitch: None")
            print(f"  Roll: {face.roll_angle:.2f}°" if face.roll_angle is not None else "  Roll: None")
            print(f"  Confidence: {face.face_confidence:.3f}")
            print(f"  Quality: {face.quality_score:.3f}")
            print(f"  Location: {face.location}")
            print()
    
    finally:
        session.close()

if __name__ == "__main__":
    try:
        check_identified_faces()
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

