#!/usr/bin/env python3
"""
Script to verify that all local images are available and working.
"""

import os
import re
from pathlib import Path

def verify_local_images():
    """Verify that all referenced images exist locally."""
    markdown_file = Path("data/balotario_clase_a_cat_I.md")
    images_dir = Path("static/images")

    if not markdown_file.exists():
        print(f"❌ Markdown file not found: {markdown_file}")
        return False

    if not images_dir.exists():
        print(f"❌ Images directory not found: {images_dir}")
        return False

    # Read markdown content
    with open(markdown_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # Find all local image references
    pattern = r'!\[\]\(/static/images/(img\d+\.jpg)\)'
    referenced_images = re.findall(pattern, content)

    print(f"🔍 Found {len(referenced_images)} image references in markdown")

    # Check if all referenced images exist
    missing_images = []
    existing_images = []

    for img_name in referenced_images:
        img_path = images_dir / img_name
        if img_path.exists():
            existing_images.append(img_name)
            print(f"✅ {img_name} - {img_path.stat().st_size} bytes")
        else:
            missing_images.append(img_name)
            print(f"❌ {img_name} - NOT FOUND")

    # Check for extra images
    all_local_images = list(images_dir.glob("*.jpg"))
    extra_images = []

    for img_path in all_local_images:
        if img_path.name not in referenced_images:
            extra_images.append(img_path.name)

    # Summary
    print(f"\n📊 Verification Summary:")
    print(f"✅ Images found: {len(existing_images)}")
    print(f"❌ Images missing: {len(missing_images)}")
    print(f"📁 Total local images: {len(all_local_images)}")
    print(f"➕ Extra images: {len(extra_images)}")

    if missing_images:
        print(f"\n❌ Missing images:")
        for img in missing_images:
            print(f"   - {img}")

    if extra_images:
        print(f"\n➕ Extra images (not referenced):")
        for img in extra_images:
            print(f"   - {img}")

    # Calculate total size
    total_size = sum(img.stat().st_size for img in all_local_images)
    print(f"\n💾 Total images size: {total_size / 1024 / 1024:.2f} MB")

    return len(missing_images) == 0

if __name__ == "__main__":
    print("🔍 Verifying local images...")
    success = verify_local_images()

    if success:
        print("\n🎉 All images are available locally!")
        print("💡 Your app can now run completely offline!")
    else:
        print("\n⚠️  Some images are missing. Run download_images.py to fix this.")
