"""
"warp" engine: works on any CPU, no downloads, ~0.3 s per photo.
Same pipeline as the live mode: MediaPipe finds the body, the old clothes are
painted over, and the garment is perspective-warped onto the torso.
"""
import numpy as np

from .overlay import blend_warped, cover_clothes, fit_quads, warp_dress
from .pose_detector import detect_body


def render(frame_bgr, dress_bgra, dress_color, anchors, sleeves):
    """Return (edited photo BGR, info dict), or (None, None) if no person was found."""
    detection = detect_body(frame_bgr)
    if detection is None:
        return None, None

    h, w = frame_bgr.shape[:2]
    points_px = detection["points"] * np.array([w, h], dtype=np.float32)
    fit = fit_quads(points_px[:4], dress_bgra.shape, anchors, dress_bgra)
    warped = warp_dress(frame_bgr.shape, dress_bgra, fit)
    info = {"hips_ok": detection["hips_ok"], "legs_ok": detection["legs_ok"]}
    if warped is None:
        return frame_bgr, info

    result = cover_clothes(
        frame_bgr, points_px, fit[1], detection["mask"], dress_color, sleeves,
        dress_alpha=warped[:, :, 3],
    )
    return blend_warped(result, warped), info
