// 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";
import { formatSize, truncateHead } from "../../../util/truncate.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 DiffSchema = Type.Object({
  ref: Type.Optional(Type.String({ description: "Base ref (optional)" })),
  ref2: Type.Optional(Type.String({ description: "Compare ref (optional)" })),
  path: Type.Optional(Type.String({ description: "Limit diff to path" })),
});

export const createGitDiffTool = (workspacePath: string): AgentTool => ({
  name: "git_diff",
  label: "Git Diff",
  description: "Show diff between refs, or between a ref and the working tree. Omit both refs for unstaged changes.",
  parameters: DiffSchema as any,
  execute: async (_toolCallId: string, params: any) => {
    const git = simpleGit(workspacePath);
    const args: string[] = [];

    if (params.ref && !String(params.ref).trim()) {
      throw new ToolInputError("ref must be a non-empty string");
    }
    if (params.ref2 && !String(params.ref2).trim()) {
      throw new ToolInputError("ref2 must be a non-empty string");
    }
    if (params.path && !String(params.path).trim()) {
      throw new ToolInputError("path must be a non-empty string");
    }
    if (params.ref) args.push(params.ref);
    if (params.ref2) args.push(params.ref2);
    if (params.path) args.push("--", params.path);

    const raw = await git.diff(args);
    const truncation = truncateHead(raw);

    let text = truncation.content;
    if (truncation.truncated) {
      text += `\n\n[truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)})]`;
    }

    return {
      content: [{ type: "text", text }],
      details: { path: params.path ?? null, ...(truncation.truncated ? { truncation } : {}) },
    };
  },
});
