import { resolve } from "node:path";
import { explainAppConfig } from "@wrnexus/styles";

function jsonReplacer(_key: string, value: unknown): unknown {
  if (typeof value === "function") return `[Function ${value.name || "anonymous"}]`;
  return value;
}

export async function runConfigCommand(appRoot: string, args: string[]): Promise<void> {
  const root = resolve(appRoot);
  const profile = args.find((arg) => arg.startsWith("--profile="))?.split("=")[1];
  const explained = await explainAppConfig(root, profile);
  if (args.includes("--json")) {
    console.log(JSON.stringify(explained, jsonReplacer, 2));
    return;
  }
  console.log(`WRNexus resolved configuration\n`);
  console.log(`  Root:     ${root}`);
  console.log(`  Profile:  ${explained.profile}`);
  console.log(`  Sources:  ${explained.sources.join(", ") || "framework defaults"}`);
  if (explained.issues.length) {
    console.log("\nIssues:");
    for (const issue of explained.issues) {
      console.log(`  ${issue.severity === "error" ? "✗" : "⚠"} ${issue.path}: ${issue.message}`);
    }
  }
  console.log("\nResolved value:\n");
  console.log(JSON.stringify(explained.config, jsonReplacer, 2));
}
