"""
Tests for HideoutNavigator (Shoreline Hideout Corridor Navigation).
"""

import pytest
from unittest.mock import MagicMock
from src.assistant_tool.hideout_navigator import HideoutNavigator


def test_hideout_navigator_init():
    nav = HideoutNavigator(screen_w=2560, screen_h=1440)
    assert nav.scale_x == 1.0
    assert nav.scale_y == 1.0


def test_navigate_corridor_early_exit():
    """Kiểm tra dừng sớm khi phát hiện Map Device quang học sau chặng 1."""
    logs = []
    nav = HideoutNavigator(screen_w=2560, screen_h=1440, log_callback=logs.append)

    wasd_calls = []
    def mock_send_wasd(dx, dy, dwell):
        wasd_calls.append((dx, dy, dwell))

    capture_calls = []
    def mock_capture(step_name):
        capture_calls.append(step_name)
        return f"mock/{step_name}.png"

    # Chặng 1 phát hiện luôn Map Device tại (1200, 600)
    def mock_find_device(img_path):
        if "LEG_1" in img_path:
            return (1200, 600)
        return (1175, 645)

    pos = nav.navigate_from_salvage_to_map_device(
        send_wasd_func=mock_send_wasd,
        capture_func=mock_capture,
        find_map_device_func=mock_find_device,
        fallback_pos=(1175, 645),
    )

    assert pos == (1200, 600)
    assert len(wasd_calls) == 1
    assert wasd_calls[0] == (-1.0, 1.0, 1.5)  # West
    assert "LEG_1" in capture_calls[0]


def test_navigate_corridor_full_3_legs():
    """Kiểm tra hoàn thành đủ 3 chặng khi chỉ nhìn thấy Map Device ở đích đến."""
    logs = []
    nav = HideoutNavigator(screen_w=2560, screen_h=1440, log_callback=logs.append)

    wasd_calls = []
    def mock_send_wasd(dx, dy, dwell):
        wasd_calls.append((dx, dy, dwell))

    capture_calls = []
    def mock_capture(step_name):
        capture_calls.append(step_name)
        return f"mock/{step_name}.png"

    # Chỉ thấy Map Device ở COMPLETE
    def mock_find_device(img_path):
        if "COMPLETE" in img_path:
            return (1150, 630)
        return (1175, 645)

    pos = nav.navigate_from_salvage_to_map_device(
        send_wasd_func=mock_send_wasd,
        capture_func=mock_capture,
        find_map_device_func=mock_find_device,
        fallback_pos=(1175, 645),
    )

    assert pos == (1150, 630)
    assert len(wasd_calls) == 3
    assert wasd_calls[0] == (-1.0, 1.0, 1.5)   # Leg 1: West
    assert wasd_calls[1] == (-1.0, -1.0, 3.0)  # Leg 2: South
    assert wasd_calls[2] == (0.0, -1.0, 1.8)   # Leg 3: Southeast (S+D)
    assert len(capture_calls) == 4             # 3 leg checks + 1 complete check


def test_is_at_salvage_bench_real_capture():
    """Kiểm tra nhận diện Salvage Bench trên ảnh chụp thật."""
    import os
    real_img = r"captures\20260917_195750_774_LIVE_VERIFICATION.png"
    if os.path.exists(real_img):
        nav = HideoutNavigator(screen_w=1189, screen_h=891)
        assert nav.is_at_salvage_bench(real_img) is True
