/**
 * Extract a pre-compiled example project into a new directory.
 * Users get a fully-working app after `npm install && npm run dev` —
 * no cloud compile required.
 */
import { execSync, spawn } from "child_process";
import { existsSync, mkdirSync, readdirSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import pc from "picocolors";
import prompts from "prompts";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const EXAMPLES_DIR = join(__dirname, "..", "examples");
const AVAILABLE = {
    recruitment: {
        title: "Recruitment / Hiring pipeline",
        description: "Candidates, jobs, applications — classic B2B with PII.",
        highlights: [
            "PII masking (email/phone redaction by role)",
            "Field-level guards on mass-assignment",
            "Actions with record-scoped access rules",
            "Org-scoped firewall on every table",
        ],
    },
};
function listExamples() {
    console.log(`\n${pc.bold("Available examples:")}\n`);
    for (const [slug, info] of Object.entries(AVAILABLE)) {
        console.log(`  ${pc.cyan(slug)} — ${info.title}`);
        console.log(`    ${pc.gray(info.description)}`);
        for (const h of info.highlights) {
            console.log(`    ${pc.gray("•")} ${pc.gray(h)}`);
        }
        console.log();
    }
}
function runCommand(cmd, cwd) {
    return new Promise((resolve) => {
        const child = spawn(cmd, {
            cwd,
            shell: true,
            stdio: "inherit",
        });
        child.on("close", (code) => resolve(code ?? 0));
    });
}
async function pickExample() {
    const slugs = Object.keys(AVAILABLE);
    if (slugs.length === 0) {
        console.error(pc.red("No examples bundled with this CLI."));
        return null;
    }
    if (slugs.length === 1) {
        return slugs[0];
    }
    const res = await prompts({
        type: "select",
        name: "slug",
        message: "Which example?",
        choices: slugs.map((s) => ({
            title: `${s} — ${AVAILABLE[s].title}`,
            value: s,
        })),
    });
    return res.slug ?? null;
}
export async function example(args) {
    const [nameArg, targetArg] = args;
    if (nameArg === "--help" || nameArg === "-h") {
        listExamples();
        console.log(`${pc.bold("Usage:")}`);
        console.log(`  quickback example              ${pc.gray("# pick interactively")}`);
        console.log(`  quickback example <name>       ${pc.gray("# extract into ./<name>/")}`);
        console.log(`  quickback example <name> <dir> ${pc.gray("# extract into <dir>/")}`);
        console.log();
        return;
    }
    if (nameArg === "list") {
        listExamples();
        return;
    }
    let slug;
    if (!nameArg) {
        slug = await pickExample();
        if (!slug)
            return;
    }
    else if (AVAILABLE[nameArg]) {
        slug = nameArg;
    }
    else {
        console.error(pc.red(`✖ Unknown example: ${nameArg}`));
        listExamples();
        process.exit(1);
    }
    const info = AVAILABLE[slug];
    const tarball = join(EXAMPLES_DIR, `${slug}.tar.gz`);
    if (!existsSync(tarball)) {
        console.error(pc.red(`✖ Example tarball missing: ${tarball}`));
        console.error(`This shouldn't happen. Try reinstalling @quickback-dev/cli.`);
        process.exit(1);
    }
    const dest = targetArg || slug;
    if (existsSync(dest) && readdirSync(dest).length > 0) {
        console.error(pc.red(`✖ Directory "${dest}" already exists and is not empty.`));
        process.exit(1);
    }
    mkdirSync(dest, { recursive: true });
    console.log(`\n${pc.bold(info.title)}`);
    console.log(pc.gray(info.description));
    console.log(`\nExtracting into ${pc.cyan(dest)}...`);
    execSync(`tar -xzf "${tarball}" -C "${dest}" --strip-components=1`, {
        stdio: "inherit",
    });
    console.log(`${pc.green("✓")} Extracted.`);
    const installRes = await prompts({
        type: "confirm",
        name: "install",
        message: "Run npm install now?",
        initial: true,
    });
    if (!installRes.install) {
        console.log(`\nSkipped. Run it later with:`);
        console.log(`  ${pc.cyan(`cd ${dest} && npm install`)}`);
        return;
    }
    console.log(`\n${pc.dim("$ npm install")}`);
    const installCode = await runCommand("npm install", dest);
    if (installCode !== 0) {
        console.error(pc.red(`\n✖ npm install failed (exit ${installCode}).`));
        console.error(`You can run it manually: cd ${dest} && npm install`);
        process.exit(installCode);
    }
    console.log(`${pc.green("✓")} Dependencies installed.`);
    const devRes = await prompts({
        type: "confirm",
        name: "dev",
        message: "Start the dev server (npm run dev)?",
        initial: true,
    });
    if (devRes.dev) {
        console.log(`\n${pc.dim("$ npm run dev")}\n`);
        await runCommand("npm run dev", dest);
    }
    else {
        console.log(`\n${pc.green("✓")} Ready. Start the dev server when you're ready:`);
        console.log(`  ${pc.cyan(`cd ${dest} && npm run dev`)}`);
        console.log(`\nTo modify: edit ${pc.cyan("quickback/")} and run ${pc.cyan("quickback compile")}`);
        console.log();
    }
}
//# sourceMappingURL=example.js.map