#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, "..");
const args = process.argv.slice(2);
const value = flag => { const index = args.indexOf(flag); return index >= 0 ? args[index + 1] : undefined; };
const output = value("--output");
const title = value("--title") || "新课程";
if (!output) { console.error("Usage: node scripts/scaffold.mjs --output <directory> [--title <title>]"); process.exit(2); }
const target = path.resolve(output);
if (fs.existsSync(target) && fs.readdirSync(target).length) { console.error(`Refusing to overwrite non-empty directory: ${target}`); process.exit(1); }
fs.mkdirSync(target, {recursive: true});
for (const name of ["index.html", "styles.css", "app.js"]) fs.copyFileSync(path.join(root, "assets", "starter", name), path.join(target, name));
fs.cpSync(path.join(root, "assets", "components"), path.join(target, "components"), {recursive: true});
fs.cpSync(path.join(root, "assets", "icons"), path.join(target, "icons"), {recursive: true});
fs.copyFileSync(path.join(root, "schemas", "course-manifest.schema.json"), path.join(target, "course-manifest.schema.json"));
const manifest = JSON.parse(fs.readFileSync(path.join(root, "assets", "demo", "course-manifest.json"), "utf8"));
manifest.course.title = title;
fs.writeFileSync(path.join(target, "course-manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
console.log(JSON.stringify({ok: true, output: target, files: fs.readdirSync(target).sort()}, null, 2));
