"""
Fix Missing WhatsApp Template Image
====================================

This script helps identify and fix the missing invitation image issue.
"""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))

from database import SessionLocal
from models import Event
from uuid import UUID
import os

def main():
    db = SessionLocal()
    
    print("="*80)
    print("WhatsApp Image URL Diagnostic")
    print("="*80)
    
    # Check uploads directory
    uploads_dir = Path(__file__).parent / "uploads"
    print(f"\nUploads directory: {uploads_dir}")
    print(f"Exists: {uploads_dir.exists()}")
    
    if uploads_dir.exists():
        files = list(uploads_dir.glob("*"))
        print(f"\nFiles in uploads ({len(files)} total):")
        for f in files:
            size_kb = f.stat().st_size / 1024
            print(f"  - {f.name} ({size_kb:.1f} KB)")
    
    # Check events with invitation images
    print("\n" + "-"*80)
    print("Events with invitation_image_url set:")
    print("-"*80)
    
    events = db.query(Event).filter(Event.invitation_image_url.isnot(None)).all()
    
    if not events:
        print("No events found with invitation images")
    else:
        for event in events:
            print(f"\nEvent: {event.name}")
            print(f"  ID: {event.id}")
            print(f"  Image URL: {event.invitation_image_url}")
            
            # Check if file exists
            if event.invitation_image_url:
                # Extract filename from URL
                if "/uploads/" in event.invitation_image_url:
                    filename = event.invitation_image_url.split("/uploads/")[-1]
                    file_path = uploads_dir / filename
                    exists = file_path.exists() if uploads_dir.exists() else False
                    status = "✅ EXISTS" if exists else "❌ MISSING"
                    print(f"  File: {filename} - {status}")
                    
                    if not exists and uploads_dir.exists():
                        # Suggest existing files
                        existing = list(uploads_dir.glob("*"))
                        if existing:
                            print(f"\n  Available files you could use instead:")
                            for f in existing[:5]:  # Show first 5
                                print(f"    - {f.name}")
    
    # Specific check for the problematic image
    print("\n" + "="*80)
    print("Checking Problematic Image")
    print("="*80)
    
    problem_url = "https://api-invy.dvirlabs.com/uploads/1d32b5fbab0f494cae443b4188a83ca3.jpg"
    problem_file = "1d32b5fbab0f494cae443b4188a83ca3.jpg"
    problem_path = uploads_dir / problem_file
    
    print(f"\nURL: {problem_url}")
    print(f"File: {problem_file}")
    print(f"Path: {problem_path}")
    print(f"Exists: {problem_path.exists()}")
    
    if not problem_path.exists():
        print("\n❌ This file is MISSING - this is why WhatsApp messages fail!")
        print("\nFix options:")
        print("1. Upload this image file to the uploads folder")
        print("2. Update your event to use a different image:")
        
        if uploads_dir.exists():
            existing = list(uploads_dir.glob("*.jpg")) + list(uploads_dir.glob("*.png"))
            if existing:
                suggested = existing[0]
                suggested_url = f"https://api-invy.dvirlabs.com/uploads/{suggested.name}"
                print(f"\n   Suggested: {suggested_url}")
                print(f"\n   To update your event, set invitation_image_url to:")
                print(f"   {suggested_url}")
    
    db.close()
    
    print("\n" + "="*80)
    print("Recommendation")
    print("="*80)
    print("""
To fix WhatsApp message delivery:

1. Either upload the missing image file:
   1d32b5fbab0f494cae443b4188a83ca3.jpg

2. Or update your event's invitation_image_url to use an existing file

3. Meta's server must be able to download the image at the URL you provide,
   otherwise the message will not be delivered even though you get HTTP 200.

4. Check webhook logs to see the actual delivery status.
    """)


if __name__ == "__main__":
    main()
