"""Unit Tests for OCR Coordinate Contract & Optical Perception (Doc 48 / Doc 50 / Rule 5).
========================================================================================
Kiểm thử các bất biến kiến trúc cảm biến quang học:
- INV-OCR-PORTAL-POS: find_portal_screen_pos trả về tọa độ hợp lệ nằm trong ranh giới màn hình.
- INV-OCR-MAP-DEVICE: find_map_device_screen_pos định vị chính xác Map Device trong Hideout.
- INV-OCR-ATLAS-UI: is_atlas_ui_open phân định chính xác giữa Hideout thường và giao diện Atlas/World Map.
- INV-LOADING-SCREEN-GATE: is_loading_screen phân biệt chuẩn xác giữa màn hình tải và trạng thái trong game.
"""

import os
import pytest
from PIL import Image

from src.common.vision_ocr import (
    find_portal_screen_pos,
    find_map_device_screen_pos,
    is_atlas_ui_open,
    is_loading_screen,
    find_portal_label_by_ocr,
)


def test_loading_screen_perception_contract():
    """Kiểm tra độ chính xác của bộ cảm biến màn hình tải trên dữ liệu thực tế."""
    loading_capture = "captures/pipeline_run/20260918_132025_748_STAGE2_MAP_DEVICE_VIEW.png"
    if os.path.exists(loading_capture):
        assert is_loading_screen(loading_capture) is True

    ingame_capture = "captures/reconnect/RECONNECT_SUCCESS_HIDEOUT.png"
    if os.path.exists(ingame_capture):
        assert is_loading_screen(ingame_capture) is False


def test_map_device_screen_pos_contract():
    """Kiểm tra find_map_device_screen_pos trên ảnh Hideout thực nghiệm."""
    test_files = [
        "captures/reconnect/RECONNECT_SUCCESS_HIDEOUT.png",
        "captures/cycle110_live_status.png",
    ]
    for p in test_files:
        if os.path.exists(p):
            img = Image.open(p)
            w, h = img.size
            pos_x, pos_y = find_map_device_screen_pos(p)
            assert 0 <= pos_x <= w, f"pos_x {pos_x} vượt ngoài giới hạn {w}"
            assert 0 <= pos_y <= h, f"pos_y {pos_y} vượt ngoài giới hạn {h}"


def test_portal_screen_pos_contract():
    """Kiểm tra find_portal_screen_pos trên ảnh thực tế."""
    test_files = [
        "captures/after_portal_click.png",
        "captures/cycle110_live_status.png",
        "captures/pipeline_run/20260917_182433_164_STAGE4_HIDEOUT_PORTAL_VIEW.png",
    ]
    for p in test_files:
        if os.path.exists(p):
            img = Image.open(p)
            w, h = img.size
            sx, sy = w / 2560.0, h / 1440.0
            pos_x, pos_y = find_portal_screen_pos(p, scale_x=sx, scale_y=sy)
            assert 0 <= pos_x <= w, f"portal pos_x {pos_x} vượt ngoài giới hạn {w}"
            assert 0 <= pos_y <= h, f"portal pos_y {pos_y} vượt ngoài giới hạn {h}"


def test_atlas_ui_open_contract():
    """Kiểm tra nhận diện giao diện Atlas đóng khi nhân vật đang ở Hideout bình thường."""
    test_files = [
        "captures/reconnect/RECONNECT_SUCCESS_HIDEOUT.png",
        "captures/cycle110_live_status.png",
    ]
    for p in test_files:
        if os.path.exists(p):
            assert is_atlas_ui_open(p) is False
