"""
Take a customer photo with OpenCV (the webcam of THIS computer) and save it as a JPEG.
Then upload the photo to the Colab notebook (fashn_tryon_colab.ipynb) to make the try-on picture.

    python tools/capture_photo.py                  # preview window + 3-2-1 countdown, saves into ./captures
    python tools/capture_photo.py --camera 1       # use the second camera
    python tools/capture_photo.py --no-preview     # no window (console countdown only)
    python tools/capture_photo.py --countdown 5 --out C:\\photos

Press Q or Esc in the preview window to cancel.
"""
import argparse
import os
import sys
import time
from datetime import datetime

import cv2


def open_camera(index, width=1280, height=720):
    # DirectShow starts much faster than the default backend on Windows.
    cam = cv2.VideoCapture(index, cv2.CAP_DSHOW) if os.name == "nt" else cv2.VideoCapture(index)
    if not cam.isOpened():
        return None
    cam.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cam.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    return cam


def draw_overlay(frame, text, guide=True):
    """Big countdown number plus a simple outline: fit head, shoulders and hips inside it."""
    h, w = frame.shape[:2]
    shown = frame.copy()
    if guide:
        cx = w // 2
        cv2.ellipse(shown, (cx, int(h * 0.16)), (int(h * 0.07), int(h * 0.09)), 0, 0, 360, (255, 255, 255), 2)
        cv2.rectangle(shown, (int(cx - h * 0.2), int(h * 0.27)), (int(cx + h * 0.2), int(h * 0.97)), (255, 255, 255), 2)
    if text:
        cv2.putText(shown, text, (w // 2 - 40, h // 2 + 40), cv2.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), 10)
        cv2.putText(shown, text, (w // 2 - 40, h // 2 + 40), cv2.FONT_HERSHEY_SIMPLEX, 4, (0, 0, 0), 4)
    return shown


def capture(camera_index=0, out_dir="captures", countdown=3, preview=True):
    """Returns the saved file path, or None if cancelled / the camera could not be used."""
    cam = open_camera(camera_index)
    if cam is None:
        print(f"ERROR: could not open camera {camera_index}. Close other apps that use the camera, "
              "or try --camera 1.")
        return None
    os.makedirs(out_dir, exist_ok=True)
    try:
        # Let the camera adjust its exposure for a moment.
        for _ in range(15):
            cam.read()

        start = time.time()
        frame = None
        while True:
            ok, frame = cam.read()
            if not ok:
                print("ERROR: the camera stopped delivering images.")
                return None
            remaining = countdown - int(time.time() - start)
            if preview:
                cv2.imshow("Customer photo (Q = cancel)", draw_overlay(frame, str(max(remaining, 0)) if remaining > 0 else ""))
                if cv2.waitKey(1) & 0xFF in (ord("q"), ord("Q"), 27):
                    print("Cancelled.")
                    return None
            elif remaining > 0:
                print(remaining, flush=True)
                time.sleep(1)
            if remaining <= 0:
                break

        path = os.path.join(out_dir, datetime.now().strftime("customer_%Y%m%d_%H%M%S.jpg"))
        cv2.imwrite(path, frame, [cv2.IMWRITE_JPEG_QUALITY, 95])  # NOT mirrored: shows the customer as others see them
        print("Saved:", path)
        return path
    finally:
        cam.release()
        if preview:
            cv2.destroyAllWindows()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--camera", type=int, default=0, help="camera number (default 0)")
    parser.add_argument("--out", default="captures", help="folder for the photos (default ./captures)")
    parser.add_argument("--countdown", type=int, default=3, help="seconds before the photo (default 3)")
    parser.add_argument("--no-preview", action="store_true", help="do not open a preview window")
    args = parser.parse_args()
    sys.exit(0 if capture(args.camera, args.out, args.countdown, not args.no_preview) else 1)
