import { runMdschema } from "../mdschema";
import { ALL_SCHEMAS } from "../schemas";
import { buildCheckTargets } from "./lib/discovery";

export type { CheckTarget } from "./lib/discovery";

export async function runCheck(
  config: { modulesRoot?: string; appRoot?: string },
  cwd: string,
): Promise<number> {
  const targets = buildCheckTargets(config);

  const results = await Promise.all(
    targets.map(async (target) => {
      const schemaPath = ALL_SCHEMAS[target.schemaKey];
      if (!schemaPath) {
        console.error(`Unknown schema key: ${target.schemaKey}`);
        return 2;
      }
      const { exitCode, stdout, stderr } = await runMdschema(
        ["check", target.glob, "--schema", schemaPath],
        cwd,
      );

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

      return exitCode;
    }),
  );

  if (results.includes(2)) return 2;
  return results.some((code) => code !== 0) ? 1 : 0;
}
