import { getTextInput, type ToolInput } from "../../core/io/input-types";
import type { ToolResult } from "../../core/io/output-types";
import type { ToolContext } from "../../core/plugins/plugin-types";
import type { VariablesConverterOptions } from "./index";

function tokenize(input: string): string[] {
  // Add space boundaries for camelCase/PascalCase transitions
  const spaced = input
    .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
    .replace(/([A-Z])([A-Z][a-z])/g, "$1 $2");
  
  // Split on dots, underscores, hyphens, or spaces
  return spaced
    .split(/[\s._-]+/)
    .map((w) => w.trim().toLowerCase())
    .filter(Boolean);
}

export async function runVariablesConverter(
  input: ToolInput,
  options: VariablesConverterOptions,
  context?: ToolContext
): Promise<ToolResult> {
  void context;

  const text = getTextInput(input).trim();
  if (!text) {
    throw new Error("No variable name provided.");
  }

  const words = tokenize(text);
  if (words.length === 0) {
    throw new Error("Could not parse any variable names from input.");
  }

  const dot = words.join(".");
  const constant = words.map((w) => w.toUpperCase()).join("_");
  const camel = words
    .map((w, idx) => (idx === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)))
    .join("");
  const pascal = words
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join("");
  const snake = words.join("_");
  const kebab = words.join("-");

  const primary = (() => {
    if (options.toFormat === "auto") {
    // If input is uppercase or contains underscores, auto-convert to dot notation
      const isUpperOrSnake = text === text.toUpperCase() || text.includes("_");
      return isUpperOrSnake ? dot : constant;
    }

    switch (options.toFormat) {
      case "dot":
        return dot;
      case "camel":
        return camel;
      case "pascal":
        return pascal;
      case "snake":
        return snake;
      case "kebab":
        return kebab;
      case "constant":
      default:
        return constant;
    }
  })();

  return {
    type: "json",
    value: {
      input: text,
      constant,
      dot,
      camel,
      pascal,
      snake,
      kebab,
      primary,
    },
  };
}
