from pathlib import Path
import sys
import logging
from datetime import datetime

from dotenv import load_dotenv

# Add project root to path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from app.face_matcher import FaceMatcher
from models.user_model import initialize_database


def main():
    logging.basicConfig(
        level="INFO",
        format="%(asctime)s %(levelname)s %(name)s: %(message)s",
    )
    print("\n" + "=" * 60)
    print("🚀 EVENT MATCHING JOB STARTED")
    print("=" * 60)

    start_time = datetime.now()

    load_dotenv()
    initialize_database()

    try:
        matcher = FaceMatcher()

        print("\n🔍 Processing images...\n")
        delivery_summary = matcher.send_grouped_matches()

        print("\n" + "=" * 60)
        print("📊 RESULT SUMMARY")
        print("=" * 60)

        if not delivery_summary:
            print("❌ No new matches found for delivery.")
        else:
            total_users = len(delivery_summary)
            total_images = sum(len(v) for v in delivery_summary.values())

            print(f"✅ Emails sent to {total_users} users")
            print(f"🖼️ Total images delivered: {total_images}\n")

            print("📧 Detailed Results:")
            for email, image_urls in delivery_summary.items():
                print(f"\n→ {email}")
                for url in image_urls:
                    print(f"   - {url}")

        end_time = datetime.now()
        duration = (end_time - start_time).total_seconds()

        print("\n⏱️ Execution Time:", duration, "seconds")
        print("=" * 60 + "\n")

    except Exception as e:
        print("\n❌ ERROR OCCURRED")
        print("Error:", str(e))
        sys.exit(1)


if __name__ == "__main__":
    main()
