import cv2
import sys
import os
import numpy as np

def find_image_in_image(image_path1, image_path2, scales=None, threshold=0.8):
    # 이미지를 컬러로 읽어옵니다.
    img1 = cv2.imread(image_path1, cv2.IMREAD_COLOR)
    img2 = cv2.imread(image_path2, cv2.IMREAD_COLOR)
    
    # 이미지가 제대로 로드되었는지 확인합니다.
    if img1 is None:
        print("img load error1")
        return None, None, -1
    if img2 is None:
        print("img load error2")
        return None, None, -1

    best_val = -1  # 가장 높은 매칭 값을 저장할 변수
    best_loc = None  # 가장 높은 매칭 위치를 저장할 변수
    best_scale = 1.0  # 가장 높은 매칭을 기록한 스케일
    
    if scales is None:
        scales = np.arange(0.8, 1.5, 0.03)

    # 여러 스케일로 템플릿 매칭 수행
    for scale in scales:
        resized_template = cv2.resize(img2, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)
        result = cv2.matchTemplate(img1, resized_template, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        
        if max_val > best_val:
            best_val = max_val
            best_loc = max_loc
            best_scale = scale
            best_template_size = resized_template.shape[1::-1]  # (width, height)

    if best_loc is None:
        return None, None, best_val
    
    top_left = best_loc
    bottom_right = (top_left[0] + best_template_size[0], top_left[1] + best_template_size[1])

    # img1에 사각형 그리기
    cv2.rectangle(img1, top_left, bottom_right, (0, 255, 0), 2)  # 초록색 사각형

    # 매칭된 영역과 best_val 리턴
    return top_left, bottom_right, best_val

def analyze_favorite_icon(image_path, top_left, bottom_right):
    # 이미지를 컬러로 읽어옵니다.
    img = cv2.imread(image_path, cv2.IMREAD_COLOR)

    # 찜 아이콘 영역 추출
    icon_region = img[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]]

    # 해당 영역에서 평균 색상을 계산합니다.
    avg_color = np.mean(icon_region, axis=(0, 1))  # BGR 순서로 평균값 반환

    # 빨간색 성분이 충분히 많으면 '찜' 상태로 판단합니다.
    blue, green, red = avg_color
    #print(f"Average color (BGR): {blue}, {green}, {red}")

    if red > 150 and red > green and red > blue:
        return 1
    else:
        return 0

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python script.py <image_path1> <image_path2> [check_favorite]")
        sys.exit(1)

    script_dir = os.path.dirname(os.path.abspath(__file__))
    image_path1 = os.path.join(script_dir, sys.argv[1])
    image_path2 = os.path.join(script_dir, sys.argv[2])

    # 찜 아이콘 위치 찾기
    top_left, bottom_right, best_val = find_image_in_image(image_path1, image_path2)

    # argv 세 번째 인자가 있으면 찜 여부 확인
    if len(sys.argv) > 3:
        if best_val >= 0.6:
            # 찜 여부 분석
            status = analyze_favorite_icon(image_path1, top_left, bottom_right)
            print(status)
        else:
            print("0")
    else:
        print(best_val)
