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

import { readFile, stat } from "node:fs/promises";
import { Type } from "@sinclair/typebox";
import type { AgentTool } from "@mariozechner/pi-agent-core";
import { resolveReadPath, ensureWorkspacePath } from "./path-utils.js";
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "../../util/truncate.js";
import { ToolInputError } from "../../util/errors.js";

const MAX_READ_BYTES = 5 * 1024 * 1024;

const ReadSchema = Type.Object({
	path: Type.String({ description: "File path relative to workspace root" }),
	offset: Type.Optional(Type.Number({ description: "1-based starting line (default: 1)" })),
	limit: Type.Optional(Type.Number({ description: "Maximum lines to return" })),
});

export const createReadTool = (workspacePath: string): AgentTool => ({
	name: "read",
	label: "Read File",
	description: `Read a file's contents. Returns up to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB, whichever is reached first. Use offset and limit to paginate large files.`,
	parameters: ReadSchema as any,
	execute: async (_toolCallId: string, params: any) => {
		const absolutePath = resolveReadPath(params.path, workspacePath);
		ensureWorkspacePath(workspacePath, absolutePath);
		const fileStats = await stat(absolutePath);

		if (fileStats.size > MAX_READ_BYTES) {
			throw new ToolInputError(`File too large (>5MB): ${params.path}`);
		}

		const raw = await readFile(absolutePath, "utf8");
		const allLines = raw.split("\n");
		const totalFileLines = allLines.length;

		const startLine = params.offset ? Math.max(0, params.offset - 1) : 0;
		const startLineDisplay = startLine + 1;

		if (startLine >= allLines.length) {
			throw new Error(`Offset ${params.offset} is beyond end of file (${allLines.length} lines total)`);
		}

		let selectedContent: string;
		let userLimitedLines: number | undefined;
		if (params.limit !== undefined) {
			const endLine = Math.min(startLine + params.limit, allLines.length);
			selectedContent = allLines.slice(startLine, endLine).join("\n");
			userLimitedLines = endLine - startLine;
		} else {
			selectedContent = allLines.slice(startLine).join("\n");
		}

		const truncation = truncateHead(selectedContent);

		let output: string;

		if (truncation.firstLineExceedsLimit) {
			const firstLineSize = formatSize(Buffer.byteLength(allLines[startLine] ?? "", "utf-8"));
			output = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use a local file viewer to extract that single line by number.]`;
		} else if (truncation.truncated) {
			const endLineDisplay = startLineDisplay + truncation.outputLines - 1;
			const nextOffset = endLineDisplay + 1;

			output = truncation.content;

			if (truncation.truncatedBy === "lines") {
				output += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;
			} else {
				output += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;
			}
		} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {
			const remaining = allLines.length - (startLine + userLimitedLines);
			const nextOffset = startLine + userLimitedLines + 1;

			output = truncation.content;
			output += `\n\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;
		} else {
			output = truncation.content;
		}

		return {
			content: [{ type: "text", text: output }],
			details: { truncation },
		};
	},
});
