"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var analyze_exports = {};
__export(analyze_exports, {
  writeSitemap: () => writeSitemap
});
module.exports = __toCommonJS(analyze_exports);
var fs = __toESM(require("fs"));
var path = __toESM(require("path"));
var import_yaml = require("yaml");
var import_utils = require("playwright-core/lib/utils");
var import_crawler = require("./crawler");
var import_blueprint = require("./blueprint");
var import_graph = require("./graph");
function writeSitemap(sitemap, outputDir, format) {
  fs.mkdirSync(path.join(outputDir, "pages"), { recursive: true });
  const sitemapFile = path.join(outputDir, `sitemap.${format}`);
  fs.writeFileSync(sitemapFile, format === "json" ? JSON.stringify(sitemap, null, 2) : (0, import_yaml.stringify)(sitemap), "utf-8");
  for (const [url, blueprint] of Object.entries(sitemap.pages)) {
    const hash = (0, import_graph.urlToFilename)(url);
    const canonicalFile = path.join(outputDir, "pages", `${hash}.${format}`);
    fs.writeFileSync(
      canonicalFile,
      format === "json" ? JSON.stringify(blueprint, null, 2) : (0, import_yaml.stringify)(blueprint),
      "utf-8"
    );
    const mapJsonFile = path.join(outputDir, "pages", `${hash}.mapJson.json`);
    fs.writeFileSync(mapJsonFile, JSON.stringify((0, import_blueprint.buildMap)(blueprint), null, 2), "utf-8");
    const outlineFile = path.join(outputDir, "pages", `${hash}.outline.txt`);
    fs.writeFileSync(outlineFile, (0, import_blueprint.buildOutline)(blueprint), "utf-8");
  }
}
if (require.main === module) {
  const args = process.argv.slice(2);
  const urlArg = args.find((a) => !a.startsWith("--"));
  const outputDirIdx = args.indexOf("--output-dir");
  const outputDir = outputDirIdx !== -1 ? args[outputDirIdx + 1] : "dom-analysis";
  const depthIdx = args.indexOf("--depth");
  const depth = depthIdx !== -1 ? parseInt(args[depthIdx + 1], 10) : 5;
  const maxPagesIdx = args.indexOf("--max-pages");
  const maxPages = maxPagesIdx !== -1 ? parseInt(args[maxPagesIdx + 1], 10) : 50;
  const sameOriginOnly = !args.includes("--no-same-origin");
  const probeButtonsIdx = args.indexOf("--probe-buttons");
  const probeButtons = probeButtonsIdx !== -1 ? args[probeButtonsIdx + 1] : "immutable-only";
  const storageStateIdx = args.indexOf("--storage-state");
  const playwrightStoragePath = storageStateIdx !== -1 ? args[storageStateIdx + 1] : void 0;
  const formatIdx = args.indexOf("--format");
  const format = formatIdx !== -1 ? args[formatIdx + 1] : "json";
  if (!urlArg) {
    process.stderr.write("Usage: analyze.js <url> [--output-dir <dir>] [--depth <n>] [--max-pages <n>] [--no-same-origin] [--probe-buttons <mode>] [--storage-state <path>] [--format <json|yaml>]\n");
    (0, import_utils.gracefullyProcessExitDoNotHang)(1);
  }
  if (!["immutable-only", "all", "none"].includes(probeButtons)) {
    process.stderr.write(`Invalid --probe-buttons: ${probeButtons}. Must be one of: immutable-only, all, none
`);
    (0, import_utils.gracefullyProcessExitDoNotHang)(1);
  }
  if (format !== "json" && format !== "yaml") {
    process.stderr.write(`Invalid --format: ${format}. Must be json or yaml.
`);
    (0, import_utils.gracefullyProcessExitDoNotHang)(1);
  }
  const run = depth > 0 ? (0, import_crawler.crawl)(urlArg, { depth, maxPages, sameOriginOnly, probeButtons, playwrightStoragePath }) : (0, import_crawler.crawlSinglePage)(urlArg, { playwrightStoragePath });
  run.then((sitemap) => {
    writeSitemap(sitemap, outputDir, format);
    const absPath = path.resolve(outputDir, `sitemap.${format}`);
    const pageCount = Object.keys(sitemap.pages).length;
    process.stdout.write(`Sitemap written: ${absPath}
`);
    process.stdout.write(`  pages: ${pageCount}
`);
    process.stdout.write(`  edges: ${sitemap.edges.length}
`);
    process.stdout.write(`  per-page: ${path.resolve(outputDir, "pages")}/
`);
  }).catch((err) => {
    process.stderr.write(`Error: ${err.message}
`);
    (0, import_utils.gracefullyProcessExitDoNotHang)(1);
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  writeSitemap
});
