"""WAA Eval — Claude Haiku with screenshot + axtree observations, rolling 3-step context, 100 actions.

Uses the Genny agent with Claude Haiku (claude-haiku-4-5-20251001) as a multimodal agent.
Observations include a screenshot and a linearized accessibility tree element table.
Keeps the last 3 observations in context, giving the agent more history to reason from.

Prerequisites:
    Windows 11 Enterprise Evaluation ISO (see waa-cube README)
    WAA_SETUP_ISO=/path/to/Win11_Eval.iso  (or set in cubes/windows-agent-arena-cube/.env)
    ANTHROPIC_API_KEY=sk-ant-...           (or set in cubes/windows-agent-arena-cube/.env)

Usage:
    # Debug mode (1 task, sequential)
    uv run recipes/waa/haiku.py debug

    # Eval mode (all tasks, 3 workers)
    uv run recipes/waa/haiku.py
"""

import sys
from datetime import datetime

from cube import LocalInfraConfig
from waa_cube.benchmark import WAABenchmark
from waa_cube.computer import ComputerConfig

from cube_harness import make_experiment_output_dir
from cube_harness.agents.genny import GennyConfig
from cube_harness.exp_runner import run_sequentially
from cube_harness.experiment import Experiment
from cube_harness.llm import LLMConfig

WAA_HAIKU_SYSTEM_PROMPT = """\
You are a desktop automation agent controlling a real Windows 11 computer.

## Environment
- OS: Windows 11
- Today's date: {today}

## Observations
Each step you receive:
1. A screenshot of the current screen (1280×800)
2. An element table listing interactive UI elements with columns:
   index, tag, name, text, x, y, w, h
3. The active window title
4. A list of all open windows
5. Clipboard contents (if any)

Where (x, y) is the top-left corner and (w, h) is the size of each element.
To click the center of element at row i: center_x = x + w//2, center_y = y + h//2

Prefer the element table for precise coordinates; use the screenshot for visual context.
Use the window title and window list to track which application is in focus.
You will see the last 3 observations in context — use this history to track progress.

## Actions
You control the computer by calling run_pyautogui(code) with valid Python/pyautogui code.

### Common pyautogui commands
- pyautogui.click(x, y)                       — left-click at pixel coordinates
- pyautogui.rightClick(x, y)                  — right-click at pixel coordinates
- pyautogui.doubleClick(x, y)                 — double-click at pixel coordinates
- pyautogui.typewrite('text', interval=0.05)  — type text character by character
- pyautogui.hotkey('ctrl', 'c')               — press key combination
- pyautogui.press('enter')                    — press a single key
- pyautogui.scroll(x, y, clicks=-3)           — scroll (negative clicks = down)
- pyautogui.dragTo(x, y, button='left')       — drag to coordinates

### Ending the task
- Call fail() if the task CANNOT be completed (infeasible tasks)
- Call done() when the task is successfully COMPLETE

## Strategy
1. Study the element table carefully to find the element you need to interact with
2. Calculate center coordinates: center_x = x + w//2, center_y = y + h//2
3. If an unexpected dialog or popup is blocking your task, dismiss it before proceeding
4. If the task is clearly impossible (missing app, contradictory requirements), call fail() immediately
5. Prefer hotkey shortcuts over mouse clicks when practical
6. Do NOT ask for clarification — always proceed with available information
7. After completing the task, verify by checking the next observation then call done()
8. Do not loop — if an action has no effect after 2 attempts, try a completely different approach\
"""


def main(debug: bool) -> None:
    today = datetime.today().strftime("%A, %B %d, %Y")
    system_prompt = WAA_HAIKU_SYSTEM_PROMPT.format(today=today)

    output_dir = make_experiment_output_dir("genny_haiku_3obs_100actions", "waa-cube")

    llm_config = LLMConfig(model_name="claude-haiku-4-5-20251001", temperature=1.0)
    agent_config = GennyConfig(
        llm_config=llm_config,
        system_prompt=system_prompt,
        max_actions=100,
        render_last_n_obs=3,
        enable_summarize=False,
        tools_as_text=False,
    )

    tool_config = ComputerConfig(
        action_space="pyautogui",
        require_a11y_tree=True,
        require_obs_winagent=True,
        observe_after_action=True,
    )

    infra = LocalInfraConfig(cpu_cores=8, ram_gb=8)
    bench_config = WAABenchmark(tool_config=tool_config, infra=infra)

    exp = Experiment(
        name="waa_genny_haiku_3obs_100actions",
        output_dir=output_dir,
        agent_config=agent_config,
        benchmark_config=bench_config,
        infra=infra,
        max_steps=100,
    )

    if debug:
        print("\n" + "=" * 60)
        print("DEBUG MODE: Running debug task sequentially")
        print("=" * 60)
        print(f"Output directory: {output_dir}")
        print(f"Model: {llm_config.model_name}")
        print("=" * 60 + "\n")
        run_sequentially(exp)
    else:
        print("\n" + "=" * 60)
        print("EVAL MODE: Running WAA tasks with Ray")
        print("=" * 60)
        print(f"Output directory: {output_dir}")
        print(f"Model: {llm_config.model_name}")
        print("Running sequentially (1 VM at a time)")
        print("=" * 60 + "\n")
        run_sequentially(exp)


if __name__ == "__main__":
    debug = len(sys.argv) > 1 and sys.argv[1] == "debug"
    main(debug)
