import cv2
import sys
import os
import pytesseract
import re

def find_image_in_image(image_path1, image_path2):
    # 이미지를 읽어옵니다.
    img1 = cv2.imread(image_path1, cv2.IMREAD_COLOR)
    img2 = cv2.imread(image_path2, cv2.IMREAD_COLOR)
    
    # 이미지가 제대로 로드되었는지 확인합니다.
    if img1 is None:
        print("img load error")
        return False
    if img2 is None:
        print("img load error")
        return False
    
    # img2가 img1 안에 있는지 확인합니다.
    result = cv2.matchTemplate(img1, img2, cv2.TM_CCOEFF_NORMED)
    
    # 템플릿 매칭의 최대 값과 위치를 찾습니다.
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    
    # 매칭 정확도 임계값 설정 (0.8 이상이면 매칭된 것으로 간주)
    threshold = 0.8
    
    if max_val >= threshold:
        return True
    else:
        return False

def extract_text(image_path):
    # 이미지에서 텍스트 추출
    img = cv2.imread(image_path)
    if img is None:
        print(f"Error: Failed to load image from {image_path}", file=sys.stderr)
        return None
    
    # OCR 엔진 설정
    custom_config = r'--oem 3 --psm 6'  # OCR 엔진 옵션 설정
    extracted_text = pytesseract.image_to_string(img, config=custom_config)
    
    # 영어, 숫자, 한글만 남기고 공백 및 특수문자 제거
    filtered_text = re.sub(r'[^ㄱ-ㅎㅏ-ㅣ가-힣0-9]', '', extracted_text)
    
    return filtered_text

if __name__ == "__main__":
    # PHP에서 전달한 인자를 받습니다.
    if len(sys.argv) < 3:
        print("error")
        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])
    #desired_text = sys.argv[3]
    
    # 이미지 비교 수행
    result = find_image_in_image(image_path1, image_path2)
    if result:
        print("true")
    else:
        print("false")
    # 결과 출력result
    #if not result:
    #    print("false")
    #    sys.exit(0)
        
    # 이미지에서 텍스트 추출 및 필터링
    #extracted_text = extract_text(image_path1)
    
    # 특정 패턴 확인 (대소문자 구분 없이)
    #if re.search(desired_text, extracted_text, re.IGNORECASE):
    #    print("true")
    #else:
    #    print("false")
