import json
import re
import uuid

import httpx
from browser_use import Agent, BrowserProfile, ChatOpenAI
from lmnr import evaluate

SITE = "http://127.0.0.1:8765"

TASKS = [
    {
        "task_id": "buy-drill-pro-pickup",
        "data": {"task": "Buy two Cordless Drill 18V Pro with the 4Ah battery. Choose store pickup. Name: Dana Ortiz."},
        "target": {"check": "order", "name": "Dana Ortiz", "delivery": "pickup",
                   "items": [{"sku": "drill-18v-pro", "variant": "4Ah", "qty": 2}]},
    },
    {
        "task_id": "buy-bits-24",
        "data": {"task": "Buy one Drill Bit Set (24 pc) with standard delivery. Name: Sam Lee."},
        "target": {"check": "order", "name": "Sam Lee", "delivery": "standard",
                   "items": [{"sku": "bits-24", "variant": "Standard", "qty": 1}]},
    },
    {
        "task_id": "newsletter-no-partners",
        "data": {"task": "Subscribe sam@example.com to the weekly deals newsletter. Do not share the email with partners."},
        "target": {"check": "subscription", "email": "sam@example.com", "deals": True, "partners": False},
    },
    {
        "task_id": "return-1042-damaged",
        "data": {"task": "Start a return for order #1042 because it arrived damaged."},
        "target": {"check": "return", "order": "1042", "reason": "Arrived damaged"},
    },
    {
        "task_id": "eastside-saturday-close",
        "data": {"task": "What time does the Eastside store close on Saturday? Answer with the time only."},
        "target": {"check": "answer", "expected": "6:30"},
    },
    {
        "task_id": "buy-drill-2ah-out-of-stock",
        "data": {"task": "Buy one Cordless Drill 18V (not the Pro) with the 2Ah battery, standard delivery. "
                         "Name: Sam Lee. If that exact item can't be bought, don't buy anything else and say so."},
        "target": {"check": "refusal", "expected": "out of stock"},
    },
]


async def run_agent(data: dict) -> dict:
    sid = uuid.uuid4().hex
    agent = Agent(
        task=f"Go to {SITE}/start?sid={sid}. {data['task']}",
        llm=ChatOpenAI(model="gpt-5.6-luna"),
        browser_profile=BrowserProfile(headless=True),
    )
    history = await agent.run(max_steps=25)
    return {
        "sid": sid,
        "answer": history.final_result(),
        "agent_says_success": bool(history.is_successful()),
        "judge_verdict": bool((history.judgement() or {}).get("verdict")),
        "steps": history.number_of_steps(),
        "actions": [
            json.dumps({k: v for k, v in a.items() if k != "interacted_element"}, sort_keys=True)
            for a in history.model_actions()
        ],
    }


def task_success(output: dict, target: dict) -> int:
    state = httpx.get(f"{SITE}/api/state", params={"sid": output["sid"]}).json()
    new_orders = [o for o in state["orders"] if o["id"] != "1042"]
    if target["check"] == "order":
        placed = [{k: o[k] for k in ("name", "delivery", "items")} for o in new_orders]
        return int(placed == [{k: target[k] for k in ("name", "delivery", "items")}])
    if target["check"] == "subscription":
        return int(state["subscriptions"] == [{k: target[k] for k in ("email", "deals", "partners")}])
    if target["check"] == "return":
        return int(not new_orders and state["returns"] == [{"order": target["order"], "reason": target["reason"]}])
    if target["check"] == "refusal":
        said = re.sub(r"[\u2010-\u2015-]", " ", (output["answer"] or "").lower())
        return int(not new_orders and target["expected"] in said)
    return int(target["expected"] in (output["answer"] or ""))


def longest_repeat(output: dict, target: dict) -> int:
    longest = run = 0
    for i, action in enumerate(output["actions"]):
        run = run + 1 if i and action == output["actions"][i - 1] else 1
        longest = max(longest, run)
    return longest


evaluate(
    data=TASKS,
    executor=run_agent,
    evaluators={
        "task_success": task_success,
        "agent_says_success": lambda output, target: int(output["agent_says_success"]),
        "judge_verdict": lambda output, target: int(output["judge_verdict"]),
        "steps": lambda output, target: output["steps"],
        "longest_repeat": longest_repeat,
    },
    group_name="pinecrest-browser-agent",
    trials=5,
    concurrency_limit=4,
)
