export interface ToolInputValue {
  text?: string;
  files?: File[];
}

interface BaseToolInputFieldDefinition {
  key?: string;
  label?: string;
  description?: string;
  example?: string;
}

export type ToolInputFieldDefinition =
  | (BaseToolInputFieldDefinition & {
      type: "text";
      maxLength?: number;
      placeholder?: string;
      multiline?: boolean;
      rows?: number;
    })
  | (BaseToolInputFieldDefinition & {
      type: "files";
      accept?: string[];
      multiple?: boolean;
      maxSizeMb?: number;
      maxFiles?: number;
    })
  | (BaseToolInputFieldDefinition & {
      type: "text-or-files";
      accept?: string[];
      maxSizeMb?: number;
    });

export type ToolInputDefinition =
  | {
      type: "none";
    }
  | ToolInputFieldDefinition
  | {
      type: "group";
      fields: ToolInputFieldDefinition[];
    };

export interface ToolInput extends ToolInputValue {
  values?: Record<string, ToolInputValue>;
}

export function getInputValue(input: ToolInput, key = "input"): ToolInputValue {
  if (key === "input") {
    return {
      text: input.text,
      files: input.files,
    };
  }

  return input.values?.[key] ?? {};
}

export function getTextInput(input: ToolInput, key = "input"): string {
  return getInputValue(input, key).text ?? "";
}

export function getFilesInput(input: ToolInput, key = "input"): File[] | undefined {
  return getInputValue(input, key).files;
}

export function setInputValue(
  input: ToolInput,
  key: string,
  value: ToolInputValue
): ToolInput {
  if (key === "input") {
    return {
      ...input,
      text: value.text,
      files: value.files,
    };
  }

  return {
    ...input,
    values: {
      ...(input.values ?? {}),
      [key]: value,
    },
  };
}
