"""Reproduce Cradle's local grading experiments. Python 3.11, numpy, python-docx."""
from __future__ import annotations

import argparse
import ast
import csv
import dataclasses
import difflib
import hashlib
import io
import json
import logging
import random
import re
import sqlite3
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace as NS
from urllib.request import urlopen

import numpy as np
from docx import Document
from docx.shared import Pt, RGBColor


HF = "b6d17e646009d6cb63d5dd7be78807b680693f61"
ASSETS = "e28460ae734cb1b33901d232cef8747c20ccd677"
WORK = "e885130962f61fb64ac305497996a46cfc7d18f0"
WORK_041 = "ea8462dc96001c0a37d0ecc4e626f9c1339ee85f"
ANDROID = "55ddaf5edc6f6c25673aed343907d5b9dca66f84"
OSWORLD = "98c0c7082d428ab7c713446b7e740b9c502374d9"
ARCHIVE = f"https://huggingface.co/datasets/McGill-NLP/agent-reward-bench/resolve/{HF}/"


class Inputs:
    def __init__(self, cache):
        self.cache = cache
        self.cache.mkdir(parents=True, exist_ok=True)
        self.hashes = {}

    def read(self, url):
        path = self.cache / hashlib.sha256(url.encode()).hexdigest()
        if not path.exists():
            for attempt in range(3):
                try:
                    with urlopen(url, timeout=60) as stream:
                        data = stream.read()
                    break
                except OSError:
                    if attempt == 2:
                        raise
                    time.sleep(attempt + 1)
            path.write_bytes(data)
        data = path.read_bytes()
        self.hashes[url] = hashlib.sha256(data).hexdigest()
        return data

    def source(self, repo, rev, file):
        return self.read(f"https://raw.githubusercontent.com/{repo}/{rev}/{file}").decode()


def definitions(source, names, namespace, owner=None, base=None):
    """Compile unchanged selected definitions; supply only their explicit dependencies."""
    tree = ast.parse(source)
    nodes = tree.body
    if owner:
        nodes = next(n.body for n in nodes if isinstance(n, ast.ClassDef) and n.name == owner)
    picks = [n for n in nodes if getattr(n, "name", None) in names]
    assert len(picks) == len(names), names
    if base:
        cls = ast.parse(f"class {owner}(Base): pass").body[0]
        cls.body = picks
        picks = [cls]
        namespace["Base"] = base
    module = ast.Module(body=picks, type_ignores=[])
    exec(compile(ast.fix_missing_locations(module), "<pinned upstream definitions>", "exec"), namespace)
    return namespace


def workarena(inputs):
    # Enumerate exactly the archived L1 chart retrieval task names, with all available models.
    # The eight paths are stable at the pinned dataset revision.
    models = ["GenericAgent-Qwen_Qwen2.5-VL-72B-Instruct", "GenericAgent-anthropic_claude-3.7-sonnet",
              "GenericAgent-gpt-4o-2024-11-20", "GenericAgent-meta-llama_Llama-3.3-70B-Instruct"]
    tasks = ["workarena.servicenow.multi-chart-min-max-retrieval", "workarena.servicenow.multi-chart-value-retrieval"]
    labels = list(csv.DictReader(io.StringIO(inputs.read(ARCHIVE + "data/annotations.csv").decode())))
    def fetch(pair):
        model, task = pair
        exp = model + "_on_workarena.servicenow"
        file = f"cleaned/workarena/{model}/{exp}/{task}.json"
        d = json.loads(inputs.read(ARCHIVE + file))
        ratings = [r["trajectory_success"] for r in labels if
                   (r["model_name"], r["exp_name"], r["task_id"]) == (model, exp, task)]
        return d, {"model": model, "task": task, "file": file, "human_ratings": ratings,
                   "archived_reward": d["summary_info"]["cum_reward"]}
    with ThreadPoolExecutor(4) as pool:
        runs = list(pool.map(fetch, [(m, t) for m in models for t in tasks]))
    d, _ = next((d, r) for d, r in runs if "anthropic" in r["model"] and "value" in r["task"])
    chart = None
    for step in d["steps"]:
        tree = step.get("axtree") or ""
        end = tree.find("button 'View chart menu, Configuration Item by Manufacturer'")
        block = tree[:end].rsplit("SvgRoot 'Interactive chart'", 1)[-1] if end >= 0 else ""
        series = re.findall(r"image '(\d+)\. (.+?), ([\d,]+)\.'", block)
        if len(series) == 13 and [int(i) for i, _, _ in series] == list(range(1, 14)):
            chart = {label: int(count.replace(",", "")) for _, label, count in series}
            break
    assert chart and "Canon" in chart
    total = sum(chart.values())
    last_action = [s["action"] for s in d["steps"] if s.get("action")][-1]
    expression = ast.parse(last_action, mode="eval").body
    assert isinstance(expression, ast.Call) and expression.func.id == "send_msg_to_user"
    actual = ast.literal_eval(expression.args[0])
    versions = {}
    for rev in [WORK_041, WORK]:
        src = inputs.source("ServiceNow/WorkArena", rev, "src/browsergym/workarena/tasks/dashboard.py")
        class Base:
            def validate(self, page, chat_messages):
                pass
        cls = definitions(src, {"validate"}, {"logging": logging, "np": np, "re": re,
                          "check_url_suffix_match": lambda *a, **k: True}, "DashboardRetrievalTask", Base)["DashboardRetrievalTask"]
        obj = cls()
        obj.start_url = "chart"
        obj._wait_for_ready = lambda page: None
        version_results = {}
        for precision in ["unrounded", "two_decimals"]:
            points = []
            for label, count in chart.items():
                share = count * 100 / total
                points.append({"label": label, "count": count, "percent": share if precision == "unrounded" else round(share, 2)})
            obj._get_chart_by_title = lambda page, title: (None, [{"data": points}], None)
            cases = {}
            for point in points:
                label, percent = point["label"], point["percent"]
                obj.config = {"chart_title": "Configuration Item by Manufacturer", "question": f"value; percent; {label}"}
                def score(reply):
                    return float(obj.validate(None, [{"role": "assistant", "message": reply}])[0])
                cases[label] = {"exact_correct": score(f"{percent}%"), "wrong_value": score(f"{percent + 1}%"),
                                "wrong_direction": score(f"-{percent}%"), "wrong_unit": score(f"{percent} percentage points of increase"),
                                "correct_explained": score(f"{point['count']} of {total} items, or {percent}%."),
                                "rounded_short": score(f"{percent:.2f}%")}
                if label == "Canon":
                    cases[label]["archived_reply"] = score(actual)
            version_results[precision] = cases
        versions[rev] = version_results
    return {"archive": [r for _, r in runs], "counts": chart, "total": total,
            "goal": d["goal"].strip(), "canon_percent": chart["Canon"] * 100 / total,
            "recorded_answer": actual, "versions": versions}


def calendar(inputs):
    repo = "google-research/android_world"
    def source(path):
        return inputs.source(repo, ANDROID, "android_world/" + path + ".py")
    fuzzy = definitions(source("utils/fuzzy_match_lib"), {"fuzzy_match"},
                        {"difflib": difflib, "_MIN_DIFF_SIMILARITY": 0.9})["fuzzy_match"]
    valid = definitions(source("task_evals/common_validators/sqlite_validators"), {"validate_rows_addition_integrity"},
                        {"logging": logging, "fuzzy_match_lib": NS(fuzzy_match=fuzzy)})["validate_rows_addition_integrity"]
    event_valid = definitions(source("task_evals/single/calendar/calendar_evaluators"), {"validate_event_addition_integrity"},
                              {"sqlite_validators": NS(validate_rows_addition_integrity=valid)})["validate_event_addition_integrity"]
    src = source("task_evals/single/calendar/calendar")
    task = definitions(src, {"validate_addition_integrity"}, {"calendar_evaluators": NS(validate_event_addition_integrity=event_valid)},
                       "SimpleCalendarAddOneEvent", object)["SimpleCalendarAddOneEvent"]()
    schema = source("task_evals/utils/sqlite_schema_utils")
    Row = definitions(schema, {"CalendarEvent"}, {"dataclasses": dataclasses, "SQLiteRow": object,
                      "device_constants": NS(TIMEZONE="America/Los_Angeles")})["CalendarEvent"]
    score_method = definitions(source("task_evals/common_validators/sqlite_validators"), {"is_successful"},
                               {"ROW_OBJECTS": "row_objects"}, "AddMultipleRows", object)["AddMultipleRows"].is_successful
    task.before = []
    results = []
    for i in range(7):
        day = datetime(2023, 10, 16, 17, tzinfo=timezone.utc) + timedelta(days=i)
        ts = int(day.timestamp())
        for freq in ["daily", "weekly"]:
            interval = 86400 if freq == "daily" else 604800
            event = Row(start_ts=ts, end_ts=ts + 1800, title="Project review", description="Review the project schedule.",
                        repeat_interval=interval, repeat_rule=0 if freq == "daily" else 1 << i)
            task.params = {"row_objects": [event]}
            changes = {"forever": {}, "end_after_two": {"repeat_limit": -2},
                       "end_on_date": {"repeat_limit": ts + interval * 3},
                       "wrong_frequency": {"repeat_interval": 604800 if freq == "daily" else 86400},
                       "wrong_time": {"start_ts": ts + 3600, "end_ts": ts + 5400}}
            values = {}
            for name, change in changes.items():
                candidate = dataclasses.replace(event, id=1, **change)
                task.list_rows = lambda env: [candidate]
                native = score_method(task, None)
                fixed = event_valid([], [candidate], [event], extras_compare=["repeat_rule", "repeat_interval", "repeat_limit"])
                values[name] = {"native": native, "with_limit_check": float(fixed)}
            results.append({"weekday": day.strftime("%A"), "frequency": freq, "scores": values})
    # Enumerate every direction-neutral description from the upstream event generator.
    # Only the first clause is changed. The expected and actual times, titles and
    # recurrence fields stay identical. No synthetic text is counted as an agent run.
    generator_src = source("task_evals/single/calendar/events_generator")
    constants = {n.targets[0].id: ast.literal_eval(n.value) for n in ast.parse(generator_src).body
                 if isinstance(n, ast.Assign) and n.targets[0].id in
                 {"ACTIONS", "SUBJECTS_DESCRIPTIONS", "ADDITIONAL_NOTES"}}
    phrases = []
    class Choices:
        def __init__(self, seq):
            self.sequence = iter(seq)
        def choice(self, items):
            result = next(self.sequence)
            assert result in items
            return result
    context = dict(constants)
    describe = definitions(generator_src, {"generate_event_description"}, context)["generate_event_description"]
    for action in constants["ACTIONS"]:
        for subject in constants["SUBJECTS_DESCRIPTIONS"]:
            for note in [None] + constants["ADDITIONAL_NOTES"]:
                context["random"] = Choices([action, subject, bool(note), note])
                text = describe()
                assert text.startswith("We will ")
                reference = dataclasses.replace(event, description=text)
                task.params = {"row_objects": [reference]}
                variants = {"exact": text, "case_only": text.swapcase(),
                            "opposite": text.replace("We will ", "We will not ", 1), "unrelated": "Bring the bicycle."}
                scores = {}
                repaired = {}
                for key, value in variants.items():
                    candidate = dataclasses.replace(reference, id=2, description=value)
                    task.list_rows = lambda env: [candidate]
                    scores[key] = score_method(task, None)
                    # This task quotes the description to copy. A normalized literal
                    # comparison is deliberately limited to that field and contract.
                    copied = " ".join(text.casefold().split()) == " ".join(value.casefold().split())
                    repaired[key] = float(scores[key] == 1 and copied)
                phrases.append({"text": text, "scores": scores, "with_copy_check": repaired})
    return {"recurrence": results, "descriptions": phrases}


def desktop(inputs, output):
    repo = "xlang-ai/OSWorld"
    src = inputs.source(repo, OSWORLD, "desktop_env/evaluators/metrics/docs.py")
    compare = definitions(src, {"compare_docx_tables"}, {"Document": Document, "logger": logging})["compare_docx_tables"]
    rows = []
    for task, domain in [("00fa164e-2612-4439-992e-157d019a8436", "multi_apps"),
                         ("81c425f5-78f3-4771-afd6-3d2973825947", "multi_apps")]:
        cfg = json.loads(inputs.source(repo, OSWORLD, f"evaluation_examples/examples/{domain}/{task}.json"))
        assert cfg["evaluator"]["func"] == "compare_docx_tables"
        expected = cfg["evaluator"]["expected"]["path"].replace("/main/", f"/{ASSETS}/")
        gold = inputs.read(expected)
        options = cfg["evaluator"].get("options", {})
        def score(doc, name):
            path = output / (task + "-" + name + ".docx")
            doc.save(path)
            return compare(io.BytesIO(gold), path, **options)
        doc = Document(io.BytesIO(gold))
        assert len(doc.tables) == 1
        scores = {"gold_roundtrip": score(doc, "roundtrip")}
        if task.startswith("00fa"):
            table = doc.tables[0]._tbl
            assert "Main Results" in "".join(table.getprevious().xpath(".//w:t/text()"))
            for section in ["1. Introduction", "2. Related Work", "3.1 Internal Structure", "4.1 Task Definition"]:
                heading = next(p for p in doc.paragraphs if p.text.strip() == section)
                heading._p.addnext(table)
                assert table.getprevious() is heading._p
                scores["table_under_" + section] = score(doc, section[:1])
            # Removing all prose also removes the required section itself.
            for p in doc.paragraphs:
                p._p.getparent().remove(p._p)
            scores["only_table_remains"] = score(doc, "table_only")
        else:
            for row in doc.tables[0].rows:
                for cell in row.cells:
                    for p in cell.paragraphs:
                        for run in p.runs:
                            run.font.size = Pt(36)
                            run.font.color.rgb = RGBColor.from_string("FF00FF")
            scores["all_runs_36pt_magenta"] = score(doc, "restyled")
        doc.tables[0].cell(0, 0).text = "Incorrect"
        scores["wrong_cell"] = score(doc, "wrong_cell")
        rows.append({"task": task, "instruction": cfg["instruction"], "scores": scores, "reference": expected})
    return rows


def recipe_environment(inputs):
    repo = "google-research/android_world"
    def source(name):
        return inputs.source(repo, ANDROID, "android_world/task_evals/" + name + ".py")
    src = source("single/recipe")
    schema = source("utils/sqlite_schema_utils")
    common = source("common_validators/sqlite_validators")
    Recipe = definitions(schema, {"Recipe"}, {"dataclasses": dataclasses, "SQLiteRow": object})["Recipe"]
    schema_ns = definitions(schema, {"get_random_items", "_is_candidate_equal_to_any_result", "insert_into_db"},
                            {"dataclasses": dataclasses})
    schema_lib = NS(**{k: schema_ns[k] for k in ["get_random_items", "insert_into_db"]}, Recipe=Recipe)
    ns = {"dataclasses": dataclasses, "sqlite_schema_utils": schema_lib, "random": random.Random(0)}
    constants = {"_RECIPES", "_COMMON_INGREDIENTS", "_SERVINGS_OPTIONS", "_PREP_TIME_OPTIONS"}
    nodes = [n for n in ast.parse(src).body if isinstance(n, ast.Assign) and getattr(n.targets[0], "id", "") in constants]
    exec(compile(ast.Module(body=nodes, type_ignores=[]), "<recipe constants>", "exec"), ns)
    generate = definitions(src, {"_generate_random_recipe"}, ns)["_generate_random_recipe"]
    # Exhaust the full support of the direction string: one base recipe and one suffix.
    generator = next(n for n in ast.parse(src).body if getattr(n, "name", "") == "_generate_random_recipe")
    suffixes = next(ast.literal_eval(n.value) for n in generator.body if isinstance(n, ast.Assign)
                    and getattr(n.targets[0], "id", "") == "directions_additions")
    directions = [r.directions + " " + s for r in ns["_RECIPES"] for s in suffixes]
    remove = definitions(common, {"validate_rows_removal_integrity"}, {})["validate_rows_removal_integrity"]
    validators = NS(ROW_OBJECTS="row_objects", NOISE_ROW_OBJECTS="noise_row_objects", validate_rows_removal_integrity=remove)

    class LocalRows:
        def initialize_task(self, env):
            self.add_rows(self.params["noise_row_objects"], env)
        def add_rows(self, rows, env):
            for row in rows:
                self.db.execute(*schema_lib.insert_into_db(row, "recipes", "recipeId"))
        def list_rows(self, env):
            return [Recipe(**dict(row)) for row in self.db.execute("select * from recipes order by recipeId")]
        def is_successful(self, env):
            pass
    base = definitions(common, {"initialize_task", "is_successful"},
                       {"ROW_OBJECTS": "row_objects"}, "DeleteMultipleRows", LocalRows)["DeleteMultipleRows"]
    parent = definitions(src, {"validate_deletion_integrity"}, {"sqlite_validators": validators},
                         "_RecipeDeleteMultipleRecipes", base)["_RecipeDeleteMultipleRecipes"]
    ns.update(sqlite_validators=validators)
    task_cls = definitions(src, {"generate_random_params", "_validate_initial_state", "goal"}, ns,
                           "RecipeDeleteMultipleRecipesWithConstraint", parent)["RecipeDeleteMultipleRecipesWithConstraint"]
    # Copy the upstream class settings alongside the selected methods.
    task_node = next(n for n in ast.parse(src).body if getattr(n, "name", "") == task_cls.__name__)
    for n in task_node.body:
        if isinstance(n, ast.Assign) and n.targets[0].id in {"n_rows", "n_rows_noise"}:
            setattr(task_cls, n.targets[0].id, ast.literal_eval(n.value))
    repaired_src = src.replace("ingredient not in r.directions.lower()", "ingredient.casefold() not in r.directions.casefold()")
    repaired_src = repaired_src.replace("ingredient in r.directions.lower()", "ingredient.casefold() in r.directions.casefold()")
    repaired_cls = definitions(repaired_src, {"generate_random_params"}, ns,
                               task_cls.__name__, task_cls)[task_cls.__name__]
    entries = []
    for index, ingredient in enumerate(ns["_COMMON_INGREDIENTS"]):
        # Force just the first random choice so every weighted slot gets one trial.
        # All choices of recipes, variations and noise retain seeded upstream sampling.
        class SlotRandom(random.Random):
            def choice(self, seq):
                if seq is ns["_COMMON_INGREDIENTS"]:
                    return ingredient
                return super().choice(seq)
        ns["random"] = SlotRandom(index)
        task = task_cls()
        task.params = task_cls.generate_random_params()
        task.db_key = "recipeId"
        cols = [f'"{f.name}"' + (" INTEGER PRIMARY KEY" if f.name == "recipeId" else "")
                for f in dataclasses.fields(Recipe)]
        with sqlite3.connect(":memory:") as db:
            db.row_factory = sqlite3.Row
            task.db = db
            db.execute("CREATE TABLE recipes (" + ",".join(cols) + ")")
            task.initialize_task(None)
            noop = task.is_successful(None)
            matching = [r for r in task.before if ingredient.casefold() in r.directions.casefold()]
            db.executemany("delete from recipes where recipeId=?", [(r.recipeId,) for r in matching])
            literal = task.is_successful(None)
        # A release policy for tasks intended to require a change: offer only catalog
        # ingredients whose literal case-folded text can occur, preserving slot weights.
        feasible = any(ingredient.casefold() in s.casefold() for s in directions)
        repaired = {"offered": feasible}
        if feasible:
            ns["random"] = SlotRandom(index)
            fixed = repaired_cls()
            fixed.params = repaired_cls.generate_random_params()
            fixed.db_key = "recipeId"
            with sqlite3.connect(":memory:") as db:
                db.row_factory = sqlite3.Row
                fixed.db = db
                db.execute("CREATE TABLE recipes (" + ",".join(cols) + ")")
                fixed.initialize_task(None)
                repaired["target_count"] = len(fixed.rows_to_delete)
                repaired["unchanged"] = fixed.is_successful(None)
                ids = [(r.recipeId,) for r in fixed.before if ingredient.casefold() in r.directions.casefold()]
                db.executemany("delete from recipes where recipeId=?", ids)
                repaired["matching_deletion"] = fixed.is_successful(None)
        entries.append({"slot": index, "ingredient": ingredient, "goal": task.goal,
                        "possible_native_strings": sum(ingredient in s.lower() for s in directions),
                        "possible_casefold_strings": sum(ingredient.casefold() in s.casefold() for s in directions),
                        "target_rows": len(task.rows_to_delete), "initial_rows": len(task.before),
                        "casefold_matches_in_initial_state": len(matching),
                        "matching_recipe_titles": sorted(set(r.title for r in matching)),
                        "unchanged_reward": noop, "casefold_delete_reward": literal,
                        "experimental_nonempty_policy": repaired})
    # Follow-up restricted to slots already proven to generate zero targets. The
    # original noise filter accepts every recipe in these mixed-case slots. Skip
    # only the subsequent, provably empty 30,000-draw search for a target.
    sensitivity = []
    for record in entries:
        if record["possible_native_strings"] or not record["possible_casefold_strings"]:
            continue
        ingredient = record["ingredient"]
        reversed_seeds = []
        for seed in range(256):
            ns["random"] = random.Random(100000 + record["slot"] * 256 + seed)
            noise = schema_lib.get_random_items(task_cls.n_rows_noise, generate, replacement=False,
                                                filter_fn=lambda r: ingredient not in r.directions.lower())
            before = [dataclasses.replace(r, recipeId=i + 1) for i, r in enumerate(noise)]
            after = [r for r in before if ingredient.casefold() not in r.directions.casefold()]
            assert remove(before, before, [], "recipeId")
            if not remove(before, after, [], "recipeId"):
                reversed_seeds.append(seed)
        sensitivity.append({"ingredient": ingredient, "slot": record["slot"], "seeds_tested": 256,
                            "seeds_with_reward_reversal": reversed_seeds})
    return {"base_recipes": len(ns["_RECIPES"]), "suffixes": len(suffixes), "slots": entries,
            "conditional_noise_study": sensitivity}


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--cache", type=Path, required=True)
    p.add_argument("--output", type=Path, required=True)
    p.add_argument("--examples", type=Path, help="Keep generated desktop fixtures here")
    args = p.parse_args()
    inputs = Inputs(args.cache)
    logging.disable(logging.WARNING)
    with tempfile.TemporaryDirectory() as temp:
        out = args.examples or Path(temp)
        out.mkdir(exist_ok=True, parents=True)
        data = {"workarena": workarena(inputs), "androidworld": calendar(inputs), "osworld": desktop(inputs, out),
                "recipe_environment": recipe_environment(inputs),
                "input_sha256": dict(sorted(inputs.hashes.items()))}
    args.output.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
