#!/usr/bin/env node
import { archivePage, defaultArchivePath } from "./archiver.mjs";

function parseArgs(argv) {
  const args = {
    command: argv[2],
    positional: []
  };
  for (let i = 3; i < argv.length; i += 1) {
    const arg = argv[i];
    if (!arg.startsWith("--")) {
      args.positional.push(arg);
      continue;
    }
    const [flag, inlineValue] = arg.split("=", 2);
    const key = flag.slice(2);
    if (key.startsWith("no-")) {
      args[key.slice(3)] = false;
    } else if (inlineValue !== undefined) {
      args[key] = inlineValue;
    } else if (i + 1 < argv.length && !argv[i + 1].startsWith("--")) {
      args[key] = argv[++i];
    } else {
      args[key] = true;
    }
  }
  return args;
}

function usage() {
  console.log(`Usage:
  node src/cli.mjs archive <url-or-html-file> [options]

Options:
  --archive-path <dir>       Output directory. Defaults to ARCHIVE_PATH or ${defaultArchivePath()}
  --id <id>                  Output id/file stem
  --headful                  Run browser in headful mode (requires display)
  --json                     Print a machine-readable JSON result`);
}

async function main() {
  const args = parseArgs(process.argv);
  if (!args.command || args.command === "help" || args["help"]) {
    usage();
    return;
  }
  if (args.command !== "archive") {
    throw new Error(`Unknown command: ${args.command}`);
  }
  const input = args.positional[0];
  if (!input) {
    usage();
    process.exitCode = 1;
    return;
  }

  const result = await archivePage(input, {
    archivePath: args["archive-path"],
    id: args.id,
    headless: args.headful === true ? false : undefined
  });

  if (args.json === true) {
    console.log(JSON.stringify({ ok: true, ...result }));
    return;
  }

  console.log(`Archived: ${result.sourceUrl}`);
  console.log(`Output:   ${result.filePath}`);
  if (result.externalAssets.length) {
    console.log(`External asset references remaining: ${result.externalAssets.length}`);
    for (const ref of result.externalAssets.slice(0, 20)) {
      console.log(`  ${ref}`);
    }
  } else {
    console.log("External asset references remaining: 0");
  }
  if (result.warnings.length) {
    console.log(`Warnings: ${result.warnings.length}`);
    for (const warning of result.warnings.slice(0, 20)) {
      console.log(`  ${warning}`);
    }
  }
  return result;
}

const args = parseArgs(process.argv);
main().catch((error) => {
  if (args.json === true) {
    console.log(JSON.stringify({ ok: false, error: error.message }));
  } else {
    console.error(error.message);
  }
  process.exitCode = 1;
});
