import type { ComponentRegistry } from "../registry.js";

interface ComposeInput { components: string[]; }
interface ComposeResult { jsx: string; imports: string[]; warnings: string[]; }

function toKebab(str: string): string {
  return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}

function toPascal(kebab: string): string {
  return kebab.split("-").map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
}

function generateComponentJsx(name: string, parts: readonly string[], requiredParts: readonly string[], indent: number): string {
  const pad = "  ".repeat(indent);
  const lines: string[] = [];
  if (parts.includes("Root")) {
    lines.push(`${pad}<${name}>`);
    for (const part of requiredParts) {
      if (part === "Root") continue;
      lines.push(`${pad}  <${name}.${part}>...</${name}.${part}>`);
    }
    lines.push(`${pad}</${name}>`);
  } else {
    lines.push(`${pad}<${name} />`);
  }
  return lines.join("\n");
}

/** Converts a pettyui/ export path to an ES import statement. */
function toImportLine(imp: string): string {
  const name = toPascal(imp.replace("pettyui/", ""));
  return `import { ${name} } from "${imp}";`;
}

/** Generates composed JSX from multiple components. */
export function handleCompose(registry: ComponentRegistry, input: ComposeInput): ComposeResult {
  const imports: string[] = [];
  const jsxParts: string[] = [];
  const warnings: string[] = [];

  for (const name of input.components) {
    const comp = registry.getComponent(name);
    if (!comp) { warnings.push(`Component "${name}" not found`); continue; }
    imports.push(comp.exportPath);
    jsxParts.push(generateComponentJsx(comp.meta.name, comp.meta.parts, comp.meta.requiredParts, 1));
  }

  const importLines = imports.map(toImportLine);
  const jsx = [...importLines, "", "function Component() {", "  return (", "    <>", jsxParts.join("\n"), "    </>", "  );", "}"].join("\n");

  return { jsx, imports, warnings };
}
