#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
队伍圆圈识别脚本！
    {"index": 5, "x": 1198, "y": 521}
]


def ensure_output_dir():
    """确保输出目录存在"""
    if DEBUG and not os.path.exists(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR)


def get_active_window():
    """获取当前激活窗口"""
    try:
        active_window = gw.getActiveWindow()
        if active_window and "王于兴师" in active_window.title:
            return active_window
        else:
            return None
    except Exception as e:
        print(f"获取窗口失败: {e}")
        return None


def capture_window(window):
    """截取窗口图像"""
    try:
        # 获取窗口位置和大小
        left, top, width, height = window.left, window.top, window.width, window.height
        # 截图
        screenshot = pyautogui.screenshot(region=(left, top, width, height))
        # 转换为OpenCV格式
        img = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
        
        if DEBUG:
            cv2.imwrite(os.path.join(OUTPUT_DIR, "window_screenshot.png"), img)
        
        return img
    except Exception as e:
        print(f"截图失败: {e}")
        return None


def detect_text(img):
    """检测图像中的"行"或"待"字"""
    try:
        # 转换为灰度图
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        
        # 二值化（调整阈值）
        _, binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)
        
        if DEBUG:
            cv2.imwrite(os.path.join(OUTPUT_DIR, "binary_image.png"), binary)
        
        # 查找轮廓
        contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        # 筛选轮廓（右侧区域）
        height, width = img.shape[:2]
        right_region_left = int(width * 0.75)  # 右侧25%区域
        
        text_detected = False
        for contour in contours:
            # 计算边界矩形
            x, y, w, h = cv2.boundingRect(contour)
            
            # 只处理右侧区域的轮廓
            if x < right_region_left:
                continue
            
            # 筛选合适大小的轮廓（调整大小范围）
            if w < 5 or w > 30 or h < 15 or h > 40:
                continue
            
            # 计算宽高比（文字通常是竖长的，调整范围）
            aspect_ratio = h / w
            if aspect_ratio < 1.5 or aspect_ratio > 4:
                continue
            
            # 认为找到文字
            text_detected = True
            
            if DEBUG:
                result_img = img.copy()
                cv2.rectangle(result_img, (x, y), (x+w, y+h), (0, 255, 0), 2)
                cv2.imwrite(os.path.join(OUTPUT_DIR, "detection_result.png"), result_img)
            
            # 找到一个就足够了
            break
        
        return text_detected
    except Exception as e:
        print(f"图像处理失败: {e}")
        return False


def output_result(result):
    """输出结果到控制台和文件"""
    json_string = json.dumps(result, ensure_ascii=False, indent=2)
    
    # 写入文件
    with open("detect_result.json", "w", encoding="utf-8") as f:
        f.write(json_string)
    
    # 输出JSON
    print(json_string)


def main():
    """主函数"""
    ensure_output_dir()
    
    # 获取当前窗口
    window = get_active_window()
    if not window:
        result = {
            "success": False,
            "msg": "当前窗口不是王于兴师客户端"
        }
        output_result(result)
        return
    
    # 截图
    img = capture_window(window)
    if img is None:
        result = {
            "success": False,
            "msg": "截图失败"
        }
        output_result(result)
        return
    
    # 识别"行"或"待"字
    text_detected = detect_text(img)
    if not text_detected:
        result = {
            "success": False,
            "msg": "未识别到文字"
        }
        output_result(result)
        return
    
    # 输出固定的部队坐标
    result = {
        "success": True,
        "teams": FIXED_TEAM_POSITIONS
    }
    
    output_result(result)


if __name__ == "__main__":
    main()
