// 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 { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, 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 ShowSchema = Type.Object({
  ref: Type.String({ description: "Commit hash or ref" }),
});

export const createGitShowTool = (workspacePath: string): AgentTool => ({
  name: "git_show",
  label: "Git Show",
  description: "Show commit message and diff for a given ref.",
  parameters: ShowSchema 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);
    const raw = await git.show([params.ref]);
    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: { ref: params.ref, ...(truncation.truncated ? { truncation } : {}) },
    };
  },
});
