"""Offline starter. Replace plan_calls with your own local function returning call IDs."""
import argparse
import copy
from pathlib import Path
import runpy
import sys
import unittest


def plan_calls(calls):
    return [call["id"] for call in calls]  # Bug: a redelivered call gets scheduled twice.


first = {"id": "call-1", "tool": "reminder"}
second = {"id": "call-2", "tool": "reminder"}
cases = [
    {"id": "one_call", "input": {"calls": [first], "expected": ["call-1"]}},
    {"id": "retried_call", "input": {"calls": [first, first], "expected": ["call-1"]}},
    {"id": "distinct_calls_same_tool", "input": {"calls": [first, second], "expected": ["call-1", "call-2"]}},
]


def candidate(item):
    return plan_calls(item["calls"])


def baseline(item):
    return list(dict.fromkeys(call["id"] for call in item["calls"]))


def evaluate(item, output, variant):
    return {"planned_calls": output == item["expected"]}


# The SDK can run the same cases and callbacks with compare_local(**workflow).
workflow = dict(cases=cases, checks=[{"id": "planned_calls", "label": "Schedule each distinct call once"}],
                baseline=baseline, candidate=candidate, evaluate=evaluate)


class ToolCallChecks(unittest.TestCase):
    def test_planned_calls(self):
        self.assertTrue(workflow["cases"], "Provide at least one case.")
        self.assertTrue(workflow["checks"], "Provide at least one named check.")
        for case in workflow["cases"]:
            with self.subTest(case=case["id"]):
                output = workflow["candidate"](copy.deepcopy(case["input"]))
                scores = workflow["evaluate"](case["input"], output, "candidate")
                for check in workflow["checks"]:
                    self.assertIs(scores.get(check["id"]), True, check.get("label") or check["id"])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Run the candidate once per offline case.")
    parser.add_argument("--offline-workflow", type=Path, help="Trusted local Python file exporting a workflow dictionary.")
    args = parser.parse_args()
    if args.offline_workflow:
        path = args.offline_workflow.resolve()
        sys.path.insert(0, str(path.parent))
        workflow = runpy.run_path(str(path))["workflow"]
    unittest.main(argv=[sys.argv[0]], verbosity=2)
