"""AutoPOE2 - Live Run Sentinel CLI Entrypoint
Tập lệnh chạy nền thụ động giám sát phiên thử nghiệm thực địa trên Client game POE2.

Sử dụng:
    python scripts/live_run_sentinel.py [--pid 22632] [--poll 0.1]
"""

import argparse
import os
import sys
import time

# Đảm bảo đường dẫn import từ thư mục gốc dự án
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

from src.assistant_tool.config import Config
from src.assistant_tool.live_sentinel import LiveRunSentinel


def main():
    parser = argparse.ArgumentParser(description="AutoPOE2 Live Run Sentinel (Passive QA Harness)")
    parser.add_argument("--pid", type=int, default=22632, help="PID của tiến trình POE2 (mặc định: 22632)")
    parser.add_argument("--log-path", type=str, default=None, help="Đường dẫn Client.txt")
    parser.add_argument("--poll", type=float, default=0.1, help="Chu kỳ polling tính theo giây (mặc định: 0.1s)")
    parser.add_argument("--incidents-dir", type=str, default="debug_harness/incidents", help="Thư mục lưu Incident Dossiers")
    args = parser.parse_args()

    log_file = args.log_path or Config.find_poe2_client_log()
    print("================================================================")
    print("      AutoPOE2 - Live Run Sentinel (Passive QA & Safety)        ")
    print("================================================================")
    print(f"Target PID       : {args.pid}")
    print(f"Log Path         : {log_file}")
    print(f"Incidents Output : {args.incidents_dir}")
    print(f"Polling Interval : {args.poll}s")
    print("Chế độ           : 100% THỤ ĐỘNG (0 input phát ra - Zero-Risk)")
    print("Nhấn Ctrl+C để kết thúc.")
    print("================================================================\n")

    sentinel = LiveRunSentinel(
        target_pid=args.pid,
        log_path=log_file,
        incidents_dir=args.incidents_dir,
        poll_interval_s=args.poll,
    )

    def on_incident(first_err, anomalies, telemetry):
        print(f"\n🚨 [CẢNH BÁO SỰ CỐ] {first_err}")
        print(f"   - Toàn bộ vi phạm: {anomalies}")
        print(f"   - Khu vực: {telemetry.get('area_name', 'Unknown')}")
        print(f"   - Tọa độ: {telemetry.get('pos_x', 0)}, {telemetry.get('pos_y', 0)}")
        print(f"   - Đã tự động đóng gói Incident Dossier vào {args.incidents_dir}\n")

    sentinel.register_incident_callback(on_incident)
    sentinel.start_monitoring()

    try:
        last_print = 0
        while True:
            time.sleep(1.0)
            now = time.time()
            if now - last_print >= 5.0:
                last_print = now
                status = sentinel.get_status()
                health_str = "HEALTHY" if status.is_healthy else f"ANOMALY ({','.join(status.active_anomalies)})"
                focus_str = "FOCUSED" if status.is_game_focused else "BACKGROUND"
                print(
                    f"[{time.strftime('%H:%M:%S')}] Status: {health_str} | "
                    f"Focus: {focus_str} | Area: '{status.current_area or 'N/A'}' | "
                    f"Incidents: {status.incidents_recorded}"
                )
    except KeyboardInterrupt:
        print("\n🛑 Nhận tín hiệu dừng từ người dùng...")
    finally:
        sentinel.stop_monitoring()
        print("✅ Live Run Sentinel đã kết thúc an toàn.")


if __name__ == "__main__":
    main()
