import type { ToolInput } from "../../core/io/input-types";
import type { ToolResult } from "../../core/io/output-types";
import type { JsonOptions } from "./index";

export async function runJsonFormatter(
  input: ToolInput,
  options: JsonOptions
): Promise<ToolResult> {
  const text = input.text || "";
  if (!text) {
    throw new Error("No text provided.");
  }

  let indentSpace: string | number = 2;
  if (options.indent === "4 spaces") {
    indentSpace = 4;
  } else if (options.indent === "tabs") {
    indentSpace = "\t";
  } else if (options.indent === "minified") {
    indentSpace = 0;
  }

  try {
    const parsed = JSON.parse(text);
    const formatted = JSON.stringify(parsed, null, indentSpace);
    
    return {
      type: "text",
      value: formatted,
    };
  } catch (cause) {
    const message = cause instanceof Error ? cause.message : String(cause);
    throw new Error(`Invalid JSON: ${message}`, { cause });
  }
}
