#!/usr/bin/env python3
"""
Script to download OpenCV DNN face detection model files.
Downloads the required prototxt and caffemodel files for face detection.
"""

import os
import urllib.request
from pathlib import Path


def download_file(url, destination):
    """Download a file from URL to destination."""
    print(f"Downloading {os.path.basename(destination)}...")
    try:
        urllib.request.urlretrieve(url, destination)
        print(f"✓ Successfully downloaded {os.path.basename(destination)}")
        return True
    except Exception as e:
        print(f"✗ Error downloading {os.path.basename(destination)}: {e}")
        return False


def main():
    """Main function to download model files."""
    # Create models directory if it doesn't exist
    models_dir = Path("models")
    models_dir.mkdir(exist_ok=True)
    
    # Model file URLs
    prototxt_url = "https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxt"
    model_url = "https://raw.githubusercontent.com/opencv/opencv_3rdparty/dnn_samples_face_detector_20170830/res10_300x300_ssd_iter_140000.caffemodel"
    
    # Destination paths
    prototxt_path = models_dir / "deploy.prototxt"
    model_path = models_dir / "res10_300x300_ssd_iter_140000.caffemodel"
    
    print("=" * 60)
    print("OpenCV DNN Face Detection Model Downloader")
    print("=" * 60)
    print()
    
    # Check if files already exist
    if prototxt_path.exists():
        print(f"⚠ {prototxt_path.name} already exists. Skipping download.")
    else:
        success = download_file(prototxt_url, prototxt_path)
        if not success:
            print("\nAlternative: You can manually download deploy.prototxt from:")
            print("https://github.com/opencv/opencv/blob/master/samples/dnn/face_detector/deploy.prototxt")
            print()
    
    if model_path.exists():
        print(f"⚠ {model_path.name} already exists. Skipping download.")
    else:
        success = download_file(model_url, model_path)
        if not success:
            print("\n⚠ Warning: The caffemodel file is large (~10MB) and may require manual download.")
            print("Alternative download methods:")
            print("1. Using wget:")
            print(f"   wget -O {model_path} {model_url}")
            print("2. Using curl:")
            print(f"   curl -L -o {model_path} {model_url}")
            print("3. Direct browser download:")
            print(f"   {model_url}")
            print()
    
    print()
    print("=" * 60)
    if prototxt_path.exists() and model_path.exists():
        print("✓ All model files are ready!")
    else:
        print("⚠ Some files may be missing. Please check the files above.")
    print("=" * 60)


if __name__ == "__main__":
    main()
