"""Small offline harness. Fixed tools, saved progress, budget and verification."""
from copy import deepcopy
from pathlib import Path
import json
import tempfile


class HarnessError(Exception):
    pass


def scripted_model(history):
    """A deterministic stand-in for a model, used to inspect the loop offline."""
    if not history:
        return {"tool": "read_tasks", "args": {}}
    if history[-1]["tool"] == "read_tasks":
        count = sum(task["done"] for task in history[-1]["result"])
        return {"tool": "write_report",
                "args": {"content": f"Completed tasks: {count}\n"}}
    return {"tool": "done", "args": {}}


class Harness:
    def __init__(self, workspace, max_steps=4):
        self.root = Path(workspace).resolve()
        self.root.mkdir(parents=True, exist_ok=True)
        self.max_steps = max_steps

    def path(self, name):
        if name not in {"tasks.json", "report.txt", "state.json"}:
            raise HarnessError("File is outside the fixed tool scope")
        p = self.root / name
        if p.is_symlink() or p.resolve().parent != self.root:
            raise HarnessError("Unexpected file location")
        return p

    def tasks(self):
        try:
            data = json.loads(self.path("tasks.json").read_text())
        except (OSError, ValueError) as exc:
            raise HarnessError("Cannot read valid tasks.json") from exc
        if not isinstance(data, list) or any(
            not isinstance(t, dict) or type(t.get("done")) is not bool
            for t in data
        ):
            raise HarnessError("Tasks must be a list with boolean done fields")
        return data

    def verify(self):
        expected = f"Completed tasks: {sum(t['done'] for t in self.tasks())}\n"
        p = self.path("report.txt")
        if not p.is_file() or p.read_text() != expected:
            raise HarnessError("Report does not match the source tasks")

    def save(self, history, status):
        # A local checkpoint, not a distributed transaction mechanism.
        state = self.path("state.json")
        with tempfile.NamedTemporaryFile(
            "w", dir=self.root, delete=False, encoding="utf-8"
        ) as tmp:
            json.dump({"history": history, "status": status}, tmp, indent=2)
            temporary = Path(tmp.name)
        temporary.replace(state)

    def run(self, model=scripted_model, resume=True):
        history = []
        state = self.path("state.json")
        if resume and state.exists():
            saved = json.loads(state.read_text())
            history = saved["history"]
            if saved["status"] == "complete":
                self.verify()
                return {"status": "complete", "history": history}
        while len(history) < self.max_steps:
            action = model(deepcopy(history))
            if not isinstance(action, dict) or set(action) != {"tool", "args"}:
                raise HarnessError("Expected tool and args fields")
            tool, args = action["tool"], action["args"]
            if not isinstance(args, dict):
                raise HarnessError("Tool args must be an object")
            if tool == "read_tasks" and not args:
                result = self.tasks()
            elif tool == "write_report" and set(args) == {"content"}:
                content = args["content"]
                if not isinstance(content, str) or len(content) > 2000:
                    raise HarnessError("Report content is invalid")
                self.path("report.txt").write_text(content)
                result = {"written": "report.txt"}
            elif tool == "done" and not args:
                self.verify()
                history.append({"tool": tool, "args": args, "result": "verified"})
                self.save(history, "complete")
                return {"status": "complete", "history": history}
            else:
                raise HarnessError("Tool or arguments are not allowed")
            history.append({"tool": tool, "args": args, "result": result})
            self.save(history, "active")
        self.save(history, "budget_exhausted")
        return {"status": "budget_exhausted", "history": history}


if __name__ == "__main__":
    root = Path("demo-workspace")
    root.mkdir(exist_ok=True)
    tasks = root / "tasks.json"
    if not tasks.exists():
        tasks.write_text(json.dumps([
            {"title": "Read about loops", "done": True},
            {"title": "Inspect tools", "done": True},
            {"title": "Add recovery", "done": False}
        ]))
    result = Harness(root).run()
    print(result["status"])
    print((root / "report.txt").read_text(), end="")
