"""AutoPOE2 - CLI Thẩm Định Giao Diện Zero-Day Sau Khi Cập Nhật Patch Mới.
=============================================================================
Công cụ thực thi kiểm chuẩn giao diện người dùng ngay sau khi POE2 tải xong patch:
- Chụp ảnh baseline mới từ cửa sổ game thật hoặc kiểm chuẩn ảnh capture thực địa.
- Kiểm tra nút TRAVERSE, Player Avatar, Waystone Tray, Inventory 60 ô, Stash và Faustus.
- Xuất báo cáo chẩn đoán xác nhận tính sẵn sàng (Patch Ready Verification).
"""

from __future__ import annotations

import argparse
from datetime import datetime
import os
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from src.assistant_tool.vision_zero_day_verifier import ZeroDayUiVerifier

if sys.stdout and hasattr(sys.stdout, "reconfigure"):
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        sys.stderr.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass


def main() -> int:
    parser = argparse.ArgumentParser(description="AutoPOE2 Zero-Day UI Baseline Verifier")
    parser.add_argument("--image", type=str, default=None, help="Đường dẫn ảnh kiểm tra (nếu không chụp trực tiếp)")
    parser.add_argument("--capture", action="store_true", help="Chụp ảnh baseline mới từ cửa sổ POE2 đang chạy")
    args = parser.parse_args()

    verifier = ZeroDayUiVerifier()
    captures_dir = ROOT / "captures"
    captures_dir.mkdir(parents=True, exist_ok=True)

    img_path = args.image

    if args.capture or (img_path is None and not any((captures_dir / f).exists() for f in ["20260914_003608_364_CLICKED_PIN_1280_560.png"])):
        print("[CAPTURE] Đang chụp baseline trực tiếp từ cửa sổ Path of Exile 2...")
        live_img, msg = verifier.capture_live_baseline()
        if live_img is not None:
            stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            img_path = str(captures_dir / f"zero_day_baseline_{stamp}.png")
            live_img.save(img_path)
            print(f"[CAPTURE OK] Đã lưu baseline mới: {img_path} ({live_img.size})")
        else:
            print(f"[CAPTURE SKIP] {msg}. Sử dụng artifact có sẵn trong captures/.")

    if img_path is None:
        default_candidate = captures_dir / "20260914_003608_364_CLICKED_PIN_1280_560.png"
        if default_candidate.exists():
            img_path = str(default_candidate)
        else:
            print("[ERROR] Không tìm thấy ảnh baseline để kiểm tra.")
            return 1

    print(f"\n[VERIFY] Bắt đầu thẩm định Zero-Day UI trên frame: {img_path}")
    report = verifier.verify_ui_frame(img_path)

    print("\n" + "=" * 70)
    print(f"KẾT QUẢ THẨM ĐỊNH GIAO DIỆN ZERO-DAY (Thời gian: {report.timestamp})")
    print(f"Độ phân giải frame: {report.resolution[0]}x{report.resolution[1]}")
    print(f"Trạng thái bản vá (Patch Ready): {'[READY - SAN THANG]' if report.is_patch_ready else '[BLOCKED - CO LOI]'}")
    print("=" * 70)

    for comp_key, comp in report.components.items():
        status_tag = "[PASS]" if comp.is_valid else "[FAIL]"
        print(f"  {status_tag:6} {comp.name:40} : {comp.details}")

    if report.warnings:
        print("\n[CẢNH BÁO]:")
        for w in report.warnings:
            print(f"  - {w}")

    if report.errors:
        print("\n[LỖI TRỌNG YẾU]:")
        for e in report.errors:
            print(f"  - {e}")

    report_out = str(captures_dir / "zero_day_verification_report.json")
    verifier.save_diagnostic_report(report, report_out)
    print(f"\n[BÁO CÁO] Đã lưu kết quả chi tiết tại: {report_out}")

    return 0 if report.is_patch_ready else 2


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