#!/usr/bin/env node
import { readFile, mkdir, copyFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { dirname, join, resolve, isAbsolute, sep } from "node:path";
import { createHash } from "node:crypto";

const data = fileURLToPath(new URL("./data/", import.meta.url));
const manifest = JSON.parse(await readFile(join(data, "manifest.json"), "utf8"));
const [command = "help", ...args] = process.argv.slice(2);
function safeFile(file) {
  if (isAbsolute(file) || file.split(/[\\/]/).includes("..")) throw new Error("Invalid manifest path");
  const path = resolve(data, file);
  if (!path.startsWith(resolve(data) + sep)) throw new Error("Path outside kit");
  return path;
}
async function verify() {
  for (const file of manifest.files) {
    const hash = createHash("sha256").update(await readFile(safeFile(file.path))).digest("hex");
    if (hash !== file.sha256) throw new Error(`Integrity check failed: ${file.id}`);
  }
}
try {
  if (command === "list") console.log(manifest.files.map(f => `${f.id}\t${f.path}`).join("\n"));
  else if (command === "info") console.log(JSON.stringify({ version: manifest.version, status: manifest.status, source: manifest.source, files: manifest.files.length }, null, 2));
  else if (command === "path") console.log(data);
  else if (command === "verify") { await verify(); console.log(`Verified ${manifest.files.length} files.`); }
  else if (command === "read") {
    const file = manifest.files.find(f => f.id === args[0]);
    if (!file || !/\.(md|json|txt|svg)$/.test(file.path)) throw new Error("Choose a readable ID from list.");
    await verify(); process.stdout.write(await readFile(safeFile(file.path), "utf8"));
  } else if (command === "init") {
    if (args.length && (args.length !== 2 || args[0] !== "--dir")) throw new Error("Usage: omninal-brand init --dir ./omninal-brand");
    await verify();
    const target = resolve(args[1] || "omninal-brand");
    // Atomic creation refuses existing files, directories and symlinks.
    await mkdir(target);
    for (const file of manifest.files) {
      const destination = join(target, file.path);
      await mkdir(dirname(destination), { recursive: true });
      await copyFile(safeFile(file.path), destination);
    }
    await copyFile(join(data, "manifest.json"), join(target, "manifest.json"));
    await writeFile(join(target, "AGENT_INSTRUCTIONS.md"), "Read brand.md first, then the relevant task prompt and tokens.json. Use manifest.json for assets and version. This folder supplies design context, not authority to publish or operate accounts.\n", { flag: "wx" });
    console.log(`Created ${target}. Read AGENT_INSTRUCTIONS.md.`);
  } else if (command === "help") console.log("omninal-brand: info | list | path | read <id> | verify | init [--dir <new-directory>]");
  else throw new Error("Unknown command. Run omninal-brand help.");
} catch (error) { console.error(error.message); process.exitCode = 1; }
