// sysutil/register-system-update.ts
// Registers the latest exported Verbatim update record with the live API.
// Usage:
//   npm run release:register -- --secret YOUR_ADMIN_SECRET
//   npm run release:register -- --record logs/system/updates/Verbatim-Beta-0.3.21.update-record.json --secret YOUR_ADMIN_SECRET

import fs from "node:fs";
import path from "node:path";

const ROOT = path.resolve(__dirname, "..");
const DEFAULT_ENDPOINT = "https://api.nodarama.com/index.php?path=admin/register-update";

function argValue(name: string): string {
  const idx = process.argv.findIndex(arg => arg === name);
  return idx >= 0 ? String(process.argv[idx + 1] || "").trim() : "";
}

function resolveRecordPath(): string {
  const explicit = argValue("--record");
  if (explicit) return path.resolve(ROOT, explicit);

  const updatesDir = path.join(ROOT, "logs", "system", "updates");
  if (!fs.existsSync(updatesDir)) throw new Error(`updates folder not found: ${updatesDir}`);

  const records = fs.readdirSync(updatesDir)
    .filter(name => name.endsWith(".update-record.json"))
    .map(name => path.join(updatesDir, name))
    .filter(file => fs.statSync(file).isFile())
    .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);

  if (!records.length) throw new Error(`no .update-record.json files found in ${updatesDir}`);
  return records[0];
}

function readSecret(): string {
  const secret = argValue("--secret") || process.env.NV_ADMIN_SECRET || "";
  if (!secret) {
    throw new Error("missing admin secret. Use: npm run release:register -- --secret YOUR_ADMIN_SECRET");
  }
  return secret;
}

async function main(): Promise<void> {
  const recordPath = resolveRecordPath();
  const endpoint = argValue("--endpoint") || DEFAULT_ENDPOINT;
  const secret = readSecret();
  const body = fs.readFileSync(recordPath, "utf8");
  const record = JSON.parse(body);

  console.log(`registering update: ${path.relative(ROOT, recordPath)}`);
  console.log(`version: ${record.version || ""}`);
  console.log(`package: ${record.package_file || record.packageFile || ""}`);
  console.log(`endpoint: ${endpoint}`);

  const response = await fetch(endpoint, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Admin-Secret": secret
    },
    body
  });

  const text = await response.text();
  let data: any = {};
  try { data = text ? JSON.parse(text) : {}; } catch { data = { raw: text }; }

  if (!response.ok || data.ok === false) {
    console.error("register failed:", JSON.stringify(data, null, 2));
    process.exit(1);
  }

  console.log("register complete:");
  console.log(JSON.stringify(data, null, 2));
}

main().catch(err => {
  console.error(`register failed: ${err?.message || String(err)}`);
  process.exit(1);
});
