/**
 * `wrnexus eject <name...>` — copy a Wire UI component's `.wrn` source into the
 * app's `app/components/`, so you fully own and can edit it. The auto-discovered
 * library version is shadowed by the app copy (same name → app wins).
 */

import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { join, resolve } from "node:path";
import { uiComponentNames, uiComponentPath } from "@wrnexus/ui/registry";

export function runEject(appRoot: string, names: string[]): void {
  const root = resolve(appRoot);
  const dest = join(root, "app", "components");
  const available = uiComponentNames();

  if (names.length === 0) {
    console.log("Usage: wrnexus eject <name...>\n\nAvailable components:");
    console.log("  " + available.join(", "));
    return;
  }

  mkdirSync(dest, { recursive: true });
  for (const requestedName of names) {
    const name = available.find(
      (componentName) => componentName.toLowerCase() === requestedName.toLowerCase(),
    );

    if (!name) {
      console.error(`✗ Unknown component "${requestedName}". Available: ${available.join(", ")}`);
      continue;
    }

    const src = uiComponentPath(name);
    const out = join(dest, `${name}.wrn`);
    if (existsSync(out)) {
      console.error(`✗ ${name}: app/components/${name}.wrn already exists — skipped`);
      continue;
    }
    copyFileSync(src, out);
    console.log(`✓ Ejected ${name} -> app/components/${name}.wrn`);
  }
}
