#!/usr/bin/env python3
"""
Test script to debug EXIF date extraction from photos.
Run this to see what EXIF data is available in your photos.
"""

import sys
import os
from pathlib import Path
from PIL import Image
from datetime import datetime

# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from src.web.services.photo_service import extract_exif_date


def test_exif_extraction(image_path: str):
    """Test EXIF extraction from a single image."""
    print(f"\n{'='*60}")
    print(f"Testing: {image_path}")
    print(f"{'='*60}")
    
    if not os.path.exists(image_path):
        print(f"❌ File not found: {image_path}")
        return
    
    # Try to open with PIL
    try:
        with Image.open(image_path) as img:
            print(f"✅ Image opened successfully")
            print(f"   Format: {img.format}")
            print(f"   Size: {img.size}")
            
            # Try getexif()
            exifdata = None
            try:
                exifdata = img.getexif()
                print(f"✅ getexif() worked: {len(exifdata) if exifdata else 0} tags")
            except Exception as e:
                print(f"❌ getexif() failed: {e}")
            
            # Try _getexif() (deprecated)
            old_exif = None
            try:
                if hasattr(img, '_getexif'):
                    old_exif = img._getexif()
                    print(f"✅ _getexif() worked: {len(old_exif) if old_exif else 0} tags")
                else:
                    print(f"⚠️  _getexif() not available")
            except Exception as e:
                print(f"❌ _getexif() failed: {e}")
            
            # Check for specific date tags
            date_tags = {
                306: "DateTime",
                36867: "DateTimeOriginal",
                36868: "DateTimeDigitized",
            }
            
            print(f"\n📅 Checking date tags:")
            found_any = False
            
            if exifdata:
                for tag_id, tag_name in date_tags.items():
                    try:
                        if tag_id in exifdata:
                            value = exifdata[tag_id]
                            print(f"   ✅ {tag_name} ({tag_id}): {value}")
                            found_any = True
                        else:
                            print(f"   ❌ {tag_name} ({tag_id}): Not found")
                    except Exception as e:
                        print(f"   ⚠️  {tag_name} ({tag_id}): Error - {e}")
            
            # Try EXIF IFD
            if exifdata and hasattr(exifdata, 'get_ifd'):
                try:
                    exif_ifd = exifdata.get_ifd(0x8769)
                    if exif_ifd:
                        print(f"\n📋 EXIF IFD found: {len(exif_ifd)} tags")
                        for tag_id, tag_name in date_tags.items():
                            if tag_id in exif_ifd:
                                value = exif_ifd[tag_id]
                                print(f"   ✅ {tag_name} ({tag_id}) in IFD: {value}")
                                found_any = True
                except Exception as e:
                    print(f"   ⚠️  EXIF IFD access failed: {e}")
            
            if not found_any:
                print(f"   ⚠️  No date tags found in EXIF data")
            
            # Try our extraction function
            print(f"\n🔍 Testing extract_exif_date():")
            extracted_date = extract_exif_date(image_path)
            if extracted_date:
                print(f"   ✅ Extracted date: {extracted_date}")
            else:
                print(f"   ❌ No date extracted")
                
    except Exception as e:
        print(f"❌ Error opening image: {e}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python test_exif_extraction.py <image_path>")
        print("\nExample:")
        print("  python test_exif_extraction.py /path/to/photo.jpg")
        sys.exit(1)
    
    image_path = sys.argv[1]
    test_exif_extraction(image_path)

