import { BestAgentError } from "@best-agent/foundation";
import type { ToolInputValue } from "@best-agent/protocol";

export function parsePromptToolDirectiveInput(toolName: string, input: string): ToolInputValue {
  const trimmed = input.trim();
  const looksStructured =
    (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
    (trimmed.startsWith("[") && trimmed.endsWith("]"));
  if (!looksStructured) {
    if (toolName === "read-file") {
      const match = trimmed.match(/^(?<path>.+):(?<start>\d+)-(?<end>\d+)$/u);
      if (match?.groups) {
        return {
          end_line: Number(match.groups.end),
          path: match.groups.path,
          start_line: Number(match.groups.start),
        };
      }
      return { path: trimmed };
    }
    if (toolName === "shell") {
      return { command: trimmed };
    }
    return trimmed;
  }
  try {
    return JSON.parse(trimmed) as ToolInputValue;
  } catch {
    throw new BestAgentError("PROMPT_INVALID", "Prompt tool directive input must be valid JSON.");
  }
}
