import time
import yaml
from pathlib import Path
from src.perception.screen_capture import ScreenCapture
from src.perception.ui_detector import UIDetector
from src.actuator.input_controller import InputController
from src.decision.state_machine import GameStateMachine

def load_config(config_path: str = "config/settings.yaml") -> dict:
    with open(config_path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f)

def main():
    print("==================================================")
    print("      AION 2 AUTOPLAY AGENT CORE RUNTIME        ")
    print("==================================================")

    config = load_config()
    print(f"[*] Loaded configuration for target: {config['game']['name']}")

    # Khởi tạo các tầng kiến trúc
    capture = ScreenCapture(target_fps=config["perception"]["fps_limit"])
    detector = UIDetector(config=config)
    actuator = InputController(config=config)
    fsm = GameStateMachine(config=config, detector=detector, actuator=actuator)

    print("[*] Agent initialized. Press Ctrl+C in terminal to stop.")

    target_frame_time = 1.0 / config["perception"]["fps_limit"]

    try:
        while True:
            start_time = time.perf_counter()

            # 1. Perception: Chụp khung hình
            frame = capture.grab()
            if frame is None:
                time.sleep(0.01)
                continue

            # 2. Decision & Action: Cập nhật FSM
            fsm.update(frame)

            # 3. Đồng bộ tốc độ khung hình (Frame pacing)
            elapsed = time.perf_counter() - start_time
            sleep_time = target_frame_time - elapsed
            if sleep_time > 0:
                time.sleep(sleep_time)

    except KeyboardInterrupt:
        print("\n[*] Agent stopped by user.")
    finally:
        capture.release()

if __name__ == "__main__":

    main()
