import {
  setInputValue,
  type ToolInput,
  type ToolInputDefinition,
  type ToolInputFieldDefinition,
} from "../io/input-types";
import type {
  ToolExample,
  ToolOptionsValue,
  UnknownPlimiPlugin,
} from "./plugin-types";

const DEFAULT_LABEL = "Try example";

function exampleForField(
  field: ToolInputFieldDefinition,
  fallback?: string
): string | undefined {
  if (field.type === "files") return undefined;
  return field.example ?? fallback;
}

function inputFromDefinition(
  definition: ToolInputDefinition,
  manifestExample?: string
): ToolInput | undefined {
  if (definition.type === "none") {
    return manifestExample ? {} : undefined;
  }

  if (definition.type !== "group") {
    const example = exampleForField(definition, manifestExample);
    return example
      ? setInputValue({}, definition.key ?? "input", { text: example })
      : undefined;
  }

  let nextInput: ToolInput = {};
  let hasExample = false;

  definition.fields.forEach((field) => {
    const example = exampleForField(field);
    if (!example) return;

    hasExample = true;
    nextInput = setInputValue(nextInput, field.key ?? "input", {
      text: example,
    });
  });

  return hasExample ? nextInput : undefined;
}

export function getPluginExamples(
  plugin: UnknownPlimiPlugin
): ToolExample<ToolOptionsValue>[] {
  if (plugin.examples && plugin.examples.length > 0) {
    return plugin.examples.map((example) => ({
      ...example,
      label: example.label ?? DEFAULT_LABEL,
    }));
  }

  const input = inputFromDefinition(
    plugin.manifest.input,
    plugin.manifest.example
  );

  return input ? [{ label: DEFAULT_LABEL, input }] : [];
}
