import path from "node:path";
import fs from "node:fs";
import { runMdschema } from "../mdschema";
import { MODULE_SCHEMAS, APP_COMPOSE_SCHEMAS } from "../schemas";

export function runInitModule(name: string, dir: string): number {
  const moduleDir = path.resolve(dir, name);
  fs.mkdirSync(moduleDir, { recursive: true });
  return 0;
}

export async function runInitModuleWithReadme(
  name: string,
  dir: string,
  cwd: string,
): Promise<number> {
  const initResult = runInitModule(name, dir);
  if (initResult !== 0) return initResult;

  const moduleDir = path.resolve(cwd, dir, name);
  const readmePath = path.join(moduleDir, "README.md");
  const schemaPath = MODULE_SCHEMAS.module;

  const { exitCode, stdout, stderr } = await runMdschema(
    ["generate", "--schema", schemaPath, "--output", readmePath],
    cwd,
  );

  if (stdout.trim()) console.log(stdout);
  if (stderr.trim()) console.error(stderr);

  return exitCode;
}

export function runInitApp(name: string, dir: string): number {
  const appDir = path.resolve(dir, name);
  fs.mkdirSync(appDir, { recursive: true });
  return 0;
}

export async function runInitAppWithReadme(
  name: string,
  dir: string,
  cwd: string,
): Promise<number> {
  const initResult = runInitApp(name, dir);
  if (initResult !== 0) return initResult;

  const appDir = path.resolve(cwd, dir, name);
  const readmePath = path.join(appDir, "README.md");
  const schemaPath = APP_COMPOSE_SCHEMAS.app;

  const { exitCode, stdout, stderr } = await runMdschema(
    ["generate", "--schema", schemaPath, "--output", readmePath],
    cwd,
  );

  if (stdout.trim()) console.log(stdout);
  if (stderr.trim()) console.error(stderr);

  return exitCode;
}
