import cv2, numpy as np

from helper import compute_distance

cal_circle = None             # reference circle (x,y,r)

def object_calibration(frame_vis, fingertip_idx, CIRCLE_TOUCH_THRESHOLD):
    global cal_circle
    hsv = cv2.cvtColor(frame_vis, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, np.array([10,100,100]), np.array([25,255,255]))
    masked = cv2.bitwise_and(frame_vis, frame_vis, mask=mask)
    gray = cv2.cvtColor(masked, cv2.COLOR_BGR2GRAY)
    gray = cv2.medianBlur(gray,5)
    circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100,
                                param1=50, param2=30, minRadius=10, maxRadius=300)
    if circles is not None:
        circles = np.round(circles[0]).astype(int)
        touched = [(x,y,r) for x,y,r in circles
                    if abs(compute_distance((x,y), fingertip_idx)-r) < CIRCLE_TOUCH_THRESHOLD]
        if touched:
            touched.sort(key=lambda c: abs(compute_distance((c[0],c[1]), fingertip_idx)-c[2]))
            x,y,r = touched[0]
            cal_circle = (x,y,r)
            PIXELS_PER_INCH = 2 * r
            print(f"Circle calib: {PIXELS_PER_INCH:.2f} px/inch")

def draw_cal_circle(frame_vis):
        global cal_circle
        cx,cy,cr = cal_circle
        cv2.circle(frame_vis,(cx,cy),cr,(0,0,255),2)
        cv2.drawMarker(frame_vis,(cx,cy),(0,0,255),cv2.MARKER_TILTED_CROSS,15,1)
        cv2.putText(frame_vis,f"Ref r={cr} px",(cx-cr,cy+cr+20),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),1)