import { readFileSync, accessSync } from "node:fs";
import { resolve, join } from "node:path";
import type { ComponentRegistry } from "../registry.js";

interface AddInput { component: string; targetDir?: string; }
interface AddResult { files: Array<{ path: string; content: string }>; dependencies: string[]; }

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

/** Copies a styled component from the registry to the user's project. */
export function handleAdd(registry: ComponentRegistry, input: AddInput): AddResult | null {
  const comp = registry.getComponent(input.component);
  if (!comp || !comp.hasStyledVersion) return null;

  const kebab = toKebab(comp.meta.name);
  const registryDir = resolve(import.meta.dirname, "../../../registry/src/components");
  const sourcePath = join(registryDir, `${kebab}.tsx`);

  try { accessSync(sourcePath); } catch { return null; }

  const content = readFileSync(sourcePath, "utf-8");
  const targetDir = input.targetDir ?? "src/components/ui";

  return {
    files: [{ path: join(targetDir, `${kebab}.tsx`), content }],
    dependencies: [comp.exportPath],
  };
}
