"""AutoPOE2 - Unit & Stress Tests: WinRT OCR Thread-Safety & Center Modal Fast-Path
Phân hệ: Sư đoàn 2: Lead Perception Architect
Bối cảnh: Năm 2026 (Path of Exile 2 v0.5.5+, WinRT OCR, Python 3.11).

Kiểm chứng các bất biến kiến trúc:
1. INV-OCR-THREAD-SAFETY: WinRT OCR xử lý đa luồng đồng thời (50 luồng) không bao giờ dính crash 0xc0000005.
2. INV-MODAL-FAST-PATH: is_center_modal_present phát hiện nhanh (< 1ms) không cần chạy WinRT OCR.
3. 100% Authentic Data Protocol (Rule 5): Kiểm chứng trên các artifact thật trong thư mục captures/.
"""

import os
import threading
import time
import pytest
from PIL import Image

import winocr
from src.common.vision_ocr import (
    is_center_modal_present,
    safe_recognize_pil_sync,
)


def test_winocr_multi_threaded_stress_50_calls():
    """INV-OCR-THREAD-SAFETY: Chạy 50 luồng gọi OCR đồng thời, khẳng định không crash 0xc0000005."""
    test_img = Image.new("RGBA", (160, 40), color=(255, 255, 255, 255))

    errors = []
    results = []

    def worker(idx: int):
        try:
            res = safe_recognize_pil_sync(test_img)
            results.append((idx, res))
        except Exception as e:
            errors.append((idx, str(e)))

    threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(50)]
    t0 = time.perf_counter()
    for t in threads:
        t.start()
    for t in threads:
        t.join(timeout=30.0)
    elapsed = time.perf_counter() - t0

    assert len(errors) == 0, f"Có {len(errors)} lỗi phát sinh trong 50 luồng OCR: {errors}"
    assert len(results) == 50, f"Chỉ hoàn thành {len(results)}/50 luồng!"
    assert elapsed < 30.0, f"Thời gian thực thi quá lâu ({elapsed:.2f}s)!"


def test_winocr_direct_sync_multithreaded():
    """Kiểm tra trực tiếp winocr.recognize_pil_sync 50 luồng đồng thời không bị rò rỉ hoặc uninit COM."""
    test_img = Image.new("RGBA", (120, 30), color=(240, 240, 240, 255))
    errors = []
    results = []

    def worker(i: int):
        try:
            res = winocr.recognize_pil_sync(test_img)
            assert isinstance(res, dict)
            results.append((i, res))
        except Exception as e:
            errors.append((i, str(e)))

    threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(50)]
    for t in threads:
        t.start()
    for t in threads:
        t.join(timeout=30.0)

    assert len(errors) == 0, f"Lỗi direct winocr call: {errors}"
    assert len(results) == 50, f"Chỉ hoàn thành {len(results)}/50 luồng direct winocr!"


def test_is_center_modal_present_on_real_ingame_captures():
    """INV-MODAL-FAST-PATH: Kiểm tra ảnh in-game thật không bị nhận nhầm thành Modal (< 5ms)."""
    from src.common.vision_ocr import _load_image
    ingame_captures = [
        "captures/reconnect/RECONNECT_STEP4_IN_GAME.png",
        "captures/pipeline_run/20260917_065154_045_DISMISS_MODALS_CHECK.png",
        "captures/pipeline_run/20260917_065332_861_DISMISS_MODALS_CHECK.png",
        "captures/pipeline_run/20260917_073322_410_DISMISS_MODALS_CHECK.png",
    ]

    tested_count = 0
    for path in ingame_captures:
        if not os.path.exists(path):
            continue
        tested_count += 1
        img_obj = _load_image(path)
        assert img_obj is not None

        t0 = time.perf_counter()
        has_modal = is_center_modal_present(img_obj)
        elapsed_ms = (time.perf_counter() - t0) * 1000.0

        assert has_modal is False, f"Ảnh in-game '{path}' bị nhận diện nhầm thành Modal!"
        assert elapsed_ms < 5.0, f"Fast-Path quá chậm ({elapsed_ms:.2f}ms >= 5ms)!"

    assert tested_count >= 1, "Cần có ít nhất 1 capture in-game để kiểm thử!"


def test_is_center_modal_present_on_real_modal_captures():
    """INV-MODAL-FAST-PATH: Nhận diện chính xác Modal khi có panel hộp thoại che trung tâm."""
    modal_captures = [
        "captures/debug_full_modal_ref.png",
        "captures/death_modal_crop.png",
    ]

    for path in modal_captures:
        if not os.path.exists(path):
            continue
        has_modal = is_center_modal_present(path)
        assert has_modal is True, f"Artifact Modal '{path}' không được nhận diện là modal!"


def test_safe_recognize_pil_sync_resilience():
    """Kiểm tra tính bền bỉ của safe_recognize_pil_sync khi truyền đầu vào None hoặc rỗng."""
    res_none = safe_recognize_pil_sync(None)
    assert res_none == {"lines": [], "text": ""}
