// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: GPL-3.0-or-later

import { Type } from "@sinclair/typebox";
import type { AgentTool } from "@mariozechner/pi-agent-core";
import simpleGit from "simple-git";
import { ToolInputError } from "../../../util/errors.js";

// Trust boundary: refs and paths are passed directly to simple-git, which is
// scoped to the workspace. The user chose to clone this repo, so its contents
// are trusted. See AGENTS.md § Workspace Sandboxing.

const CheckoutSchema = Type.Object({
  ref: Type.String({ description: "Ref to checkout" }),
});

export const createGitCheckoutTool = (workspacePath: string): AgentTool => ({
  name: "git_checkout",
  label: "Git Checkout",
  description: "Checkout a branch, tag, or commit.",
  parameters: CheckoutSchema as any,
  execute: async (_toolCallId: string, params: any) => {
    if (!String(params.ref ?? "").trim()) {
      throw new ToolInputError("ref must be a non-empty string");
    }
    const git = simpleGit(workspacePath);
    await git.checkout(params.ref);

    return {
      content: [{ type: "text", text: `Checked out ${params.ref}` }],
      details: { ref: params.ref },
    };
  },
});
