#!/usr/bin/env python3
"""
scripts/verify_inv_nav_commercial_live.py
Empirical Verification Gate for INV-NAV-TERRAIN-COMMERCIAL on Live Game Client (PID 43084).
Captures real screenshots before zoom, during dynamic camera zoom-in, and after restoration.
Validates tangent sliding vector calculation and 3D coordinate projection.
"""

import ctypes
import json
import os
import sys
import time
from typing import Dict, Any

WORKSPACE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if WORKSPACE_ROOT not in sys.path:
    sys.path.insert(0, WORKSPACE_ROOT)

from tools.autonomous_mapping_coordinator import AutonomousMappingCoordinator


def main():
    report: Dict[str, Any] = {
        "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
        "invariant": "INV-NAV-TERRAIN-COMMERCIAL",
        "live_client": {},
        "tangent_sliding_test": {},
        "projection_test": {},
        "zoom_verification": {},
        "status": "FAILED",
    }

    coordinator = AutonomousMappingCoordinator(screen_w=2560, screen_h=1440, capture_dir="captures")
    focused = coordinator.ensure_focus()
    report["live_client"]["focused"] = focused

    # 1. Test Tangent Sliding geometry
    slide_dx, slide_dy, hand = coordinator.compute_tangent_slide(
        current_x=100.0, current_y=100.0,
        desired_dx=10.0, desired_dy=0.0,
        goal_x=100.0, goal_y=150.0,
        preferred_hand=0
    )
    report["tangent_sliding_test"] = {
        "desired_heading": [10.0, 0.0],
        "goal_dir": [0.0, 50.0],
        "chosen_hand": hand,
        "slide_vector": [round(slide_dx, 4), round(slide_dy, 4)],
        "valid_orthogonal_blend": (slide_dy > 0.0 and slide_dx > 0.0),
        "correct_hand_direction": (hand == 1)
    }

    # 2. Test 3D WorldToScreen projection
    px_norm, py_norm = coordinator.project_map_device_world_to_screen(150.0, 100.0, 100.0, 100.0, is_zoomed_in=False)
    px_zoom, py_zoom = coordinator.project_map_device_world_to_screen(150.0, 100.0, 100.0, 100.0, is_zoomed_in=True)
    report["projection_test"] = {
        "dev_world": [150.0, 100.0],
        "player_world": [100.0, 100.0],
        "screen_normal": [px_norm, py_norm],
        "screen_zoomed": [px_zoom, py_zoom],
        "zoom_magnification_verified": (abs(px_zoom - 1280) > abs(px_norm - 1280))
    }

    # 3. Live Screen Capture & Dynamic Camera Zoom Test on Real Game Client
    os.makedirs("captures", exist_ok=True)
    baseline_path = coordinator.capture_step("LIVE_COMMERCIAL_NAV_BASELINE")
    report["zoom_verification"]["baseline_image"] = baseline_path

    # Perform Dynamic Camera Zoom-in (+480 wheel)
    coordinator.dynamic_camera_zoom(zoom_in=True, steps=4, step_delay=0.04)
    time.sleep(0.3)
    zoomed_path = coordinator.capture_step("LIVE_COMMERCIAL_NAV_ZOOMED_IN")
    report["zoom_verification"]["zoomed_image"] = zoomed_path

    # Restore Default Camera Zoom (-480 wheel)
    coordinator.dynamic_camera_zoom(zoom_in=False, steps=4, step_delay=0.04)
    time.sleep(0.3)
    restored_path = coordinator.capture_step("LIVE_COMMERCIAL_NAV_RESTORED")
    report["zoom_verification"]["restored_image"] = restored_path

    # Check images exist and verify file sizes
    all_captured = (
        baseline_path is not None and os.path.exists(baseline_path) and
        zoomed_path is not None and os.path.exists(zoomed_path) and
        restored_path is not None and os.path.exists(restored_path)
    )
    report["zoom_verification"]["all_files_exist"] = all_captured

    if all_captured:
        report["zoom_verification"]["file_sizes"] = {
            "baseline_bytes": os.path.getsize(baseline_path),
            "zoomed_bytes": os.path.getsize(zoomed_path),
            "restored_bytes": os.path.getsize(restored_path),
        }
        report["status"] = "SUCCESS"

    print(json.dumps(report, indent=2))
    return 0 if report["status"] == "SUCCESS" else 1


if __name__ == "__main__":
    sys.exit(main())
