#!/usr/bin/env node
// Emissar Resolve v0.1: runnable example.
// Spec: https://emissar.ai/specs/resolve/v0.1. No dependencies; Node 20 or later.
//
//   node resolve-example.mjs          walkthrough (the spec's Appendix A output)
//   node resolve-example.mjs --json   machine output, read by validate.py
//
// What it does, in order:
//   1. Normalizes sample inputs for each identifier type (section 5).
//   2. Seeds "observed" records from three real entries of Emissar's public agent directory
//      (directory-sample.json next to this file, taken from the directory export of crawl full-20260926-39db43), per section 9.
//   3. Adds three ILLUSTRATIVE claimed records (reserved example identifiers, not real claims).
//   4. Answers lookups the way section 8 specifies: 200, 308 to the canonical path, 304 on If-None-Match,
//      400 for an invalid identifier, 404 as the negative answer, 429 when the client's rate limit is spent.
// A fixed clock keeps the output reproducible; pass --now=<RFC 3339> to change it.

import { readFileSync, readdirSync } from "node:fs";
import { createHash } from "node:crypto";
import { domainToASCII, domainToUnicode, fileURLToPath } from "node:url";
import path from "node:path";

const args = process.argv.slice(2);
const JSON_MODE = args.includes("--json");
const NOW = new Date(args.find((a) => a.startsWith("--now="))?.slice(6) ?? "2026-09-26T23:00:00Z");
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../..");
const PROBLEM_BASE = "https://emissar.ai/specs/resolve/v0.1";
const DAY = 86400e3;

// ---------------------------------------------------------------- section 5.1: E.164 telephone numbers
// NANP (country code 1): NXX-NXX-XXXX, N = 2-9 (47 CFR 52.7(a), (c)). Toll-free codes per 47 CFR 52.101 practice.
const NANP_TOLL_FREE = new Set(["800", "833", "844", "855", "866", "877", "888"]);
const TEL_SEPARATORS = /[\s\-.()  -​‐-―−　]/gu;

export function normalizeTel(input) {
  if (typeof input !== "string") return fail("not a string");
  let s = input.normalize("NFKC").trim(); // NFKC maps full-width digits and plus to ASCII
  if (/^tel:/i.test(s)) {
    s = s.slice(4);
    if (s.includes(";")) return fail("tel URI parameters (extension, phone-context) are not E.164");
  }
  s = s.replace(TEL_SEPARATORS, "");
  if (!s.startsWith("+")) return fail("no leading '+' and country code; convert national numbers before lookup");
  const digits = s.slice(1);
  if (/[a-z]/i.test(digits)) return fail("letters are not allowed (vanity numbers must be converted to digits)");
  if (!/^[0-9]+$/.test(digits)) return fail("only digits may follow '+'");
  if (digits[0] === "0") return fail("country codes do not start with 0");
  if (digits.length > 15) return fail("more than 15 digits (E.164 maximum)");
  if (digits.length < 4) return fail("too short");
  let kind = "e164";
  if (digits[0] === "1") {
    if (digits.length !== 11) return fail("NANP numbers have exactly 10 digits after +1");
    const npa = digits.slice(1, 4);
    const nxx = digits.slice(4, 7);
    if (!/^[2-9]/.test(npa)) return fail("NANP area code must start with 2-9");
    if (!/^[2-9]/.test(nxx)) return fail("NANP central office code must start with 2-9");
    kind = NANP_TOLL_FREE.has(npa) ? "nanp-toll-free" : "nanp-geographic";
  }
  return { ok: true, type: "tel", value: `+${digits}`, kind };
}

// ---------------------------------------------------------------- section 5.2: domain names
const SPECIAL_USE_TLDS = new Set(["localhost", "local", "internal", "invalid", "test", "example", "onion", "arpa", "home", "lan", "alt"]);
const LDH_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;

export function normalizeDomain(input) {
  if (typeof input !== "string") return fail("not a string");
  let s = input.trim();
  if (!s) return fail("empty");
  if (/[/@:]/.test(s)) return fail("a domain only: no scheme, path, port or user part");
  if (s.endsWith(".")) s = s.slice(0, -1); // one trailing dot (the root) is dropped
  // UTS #46 mapping and Punycode via the WHATWG URL algorithm (non-transitional). It returns "" on failure.
  const ascii = domainToASCII(s);
  if (!ascii) return fail("not a valid IDNA domain name");
  if (/^[0-9.]+$/.test(ascii) || ascii.includes("[")) return fail("IP literals are not domain identifiers");
  if (ascii.length > 253) return fail("longer than 253 characters");
  const labels = ascii.split(".");
  if (labels.length < 2) return fail("single-label names are not allowed");
  // WHATWG URL does not apply STD3 (LDH) rules or DNS length checks, so check them here.
  if (!labels.every((l) => LDH_LABEL.test(l))) return fail("labels must be 1-63 letters, digits or hyphens, not starting or ending with a hyphen");
  if (/^[0-9]+$/.test(labels.at(-1))) return fail("top-level label is numeric");
  const out = { ok: true, type: "domain", value: ascii };
  const unicode = domainToUnicode(ascii);
  if (unicode !== ascii) out.display = unicode;
  if (SPECIAL_USE_TLDS.has(labels.at(-1))) out.specialUse = true; // normalizes, but lookups answer 400
  return out;
}

// ---------------------------------------------------------------- section 5.3: brand names
// Closed list of legal-form designators removed from the end (after case folding). Appendix B of the spec.
const LEGAL_FORMS = new Set([
  "inc", "incorporated", "corp", "corporation", "co", "company", "llc", "llp", "lp", "ltd", "limited", "plc",
  "ltee", "ltée", "limitee", "limitée", "ulc", "gmbh", "ag", "sa", "sas", "srl", "bv", "nv", "pty",
]);

/** Approximates Unicode NFKC_Casefold: NFKC, then toUpperCase().toLowerCase() (folds ß to ss, final sigma), then NFKC. */
const casefold = (s) => s.normalize("NFKC").toUpperCase().toLowerCase().normalize("NFKC");

export function brandKey(name, country) {
  if (typeof name !== "string" || typeof country !== "string") return fail("brand and country are required");
  const cc = country.trim().toUpperCase();
  if (!/^[A-Z]{2}$/.test(cc)) return fail("country must be an ISO 3166-1 alpha-2 code");
  const display = name.normalize("NFC").replace(/\s+/gu, " ").trim();
  if (!display || display.length > 200) return fail("brand must be 1-200 characters");
  const tokens = casefold(display).split(/[^\p{L}\p{M}\p{N}]+/u).filter(Boolean);
  while (tokens.length > 1 && LEGAL_FORMS.has(tokens.at(-1))) tokens.pop();
  const value = tokens.join("");
  if ([...value].length < 2) return fail("brand key shorter than 2 characters");
  if ([...value].length > 64) return fail("brand key longer than 64 characters");
  return { ok: true, type: "brand", value, country: cc, display };
}

function fail(error) {
  return { ok: false, error };
}

// ---------------------------------------------------------------- helpers
/** RFC 8785 (JCS) for the JSON this example produces: strings, integers, booleans, null, arrays, objects. */
function jcs(v) {
  if (v === null || typeof v !== "object") return JSON.stringify(v);
  if (Array.isArray(v)) return `[${v.map(jcs).join(",")}]`;
  return `{${Object.keys(v).filter((k) => v[k] !== undefined).sort().map((k) => `${JSON.stringify(k)}:${jcs(v[k])}`).join(",")}}`;
}
const b64url = (buf) => buf.toString("base64url");
const etagOf = (body) => `"${b64url(createHash("sha256").update(jcs(body)).digest()).slice(0, 27)}"`;
const recordId = (seed) => {
  const alphabet = "abcdefghijklmnopqrstuvwxyz234567";
  const h = createHash("sha256").update(seed).digest();
  let bits = "";
  for (const b of h) bits += b.toString(2).padStart(8, "0");
  return "rsv_" + Array.from({ length: 20 }, (_, i) => alphabet[parseInt(bits.slice(i * 5, i * 5 + 5), 2)]).join("");
};
const iso = (d) => new Date(d).toISOString();
const keyOf = (id) => (id.type === "brand" ? `brand:${id.country}:${id.value}` : `${id.type}:${id.value}`);

// ---------------------------------------------------------------- section 9: seeding from the directory export
const SEED_DOMAINS = ["opensea.io", "activecampaign.com", "modelcontextprotocol.io"];
const OBSERVED_TTL_DAYS = 35;

function latestDirectoryExport() {
  // Published copies read the sample next to this file; inside Emissar's repository the newest export is used.
  const sample = path.join(path.dirname(fileURLToPath(import.meta.url)), "directory-sample.json");
  try {
    return { file: "directory-sample.json", doc: JSON.parse(readFileSync(sample, "utf8")) };
  } catch {
    // no sample: fall through to the repository's exports
  }
  const dir = path.join(ROOT, "src", "data", "directory");
  const files = readdirSync(dir).filter((f) => f.endsWith(".json"));
  if (!files.length) throw new Error(`no directory export in ${dir}`);
  const docs = files.map((f) => ({ file: `src/data/directory/${f}`, doc: JSON.parse(readFileSync(path.join(dir, f), "utf8")) }));
  docs.sort((a, b) => String(b.doc.exportedAt).localeCompare(String(a.doc.exportedAt)));
  return docs[0];
}

/** One observed record from one directory entry, or a skip reason. Never tel or brand; nothing self-asserted is copied. */
export function seedRecord(entry) {
  const d = normalizeDomain(entry.domain);
  if (!d.ok || d.value !== entry.domain) return { skip: "domain not canonical" };
  const url = entry.card?.url;
  if (!url) return { skip: "no https card URL" };
  const host = new URL(url).hostname;
  if (host !== d.value && !host.endsWith(`.${d.value}`)) return { skip: "card served from another domain" };
  const seen = new Date(entry.lastSeen);
  if (Number.isNaN(seen.getTime())) return { skip: "no observation time" };
  const expires = new Date(seen.getTime() + OBSERVED_TTL_DAYS * DAY);
  if (expires <= NOW) return { skip: "observation expired" };
  const identifier = { type: "domain", value: d.value };
  if (d.display) identifier.display = d.display;
  return {
    record: {
      id: recordId(`crawl|${d.value}`),
      identifier,
      cardUrl: url,
      status: "active",
      source: "crawl",
      verification: {
        level: "observed",
        method: "crawl-well-known",
        lastVerifiedAt: iso(seen),
        expiresAt: iso(expires),
        evidence: [{ kind: "crawl", ref: entry.sourceCrawl, checkedAt: iso(seen) }],
      },
      updatedAt: iso(seen),
    },
  };
}

// ---------------------------------------------------------------- ILLUSTRATIVE claimed records (section 7)
// Reserved identifiers only: 555-0100..0199 are NANPA's fictitious numbers; example.com is reserved by RFC 2606.
function illustrativeClaims() {
  const verified = iso(new Date(NOW.getTime() - 3 * DAY));
  const org = { name: "Example Telecom Inc.", country: "CA", registry: { authority: "Corporations Canada", id: "0000000-0" } };
  const card = "https://agent.example.com/.well-known/agent-card.json";
  return [
    {
      id: recordId("claim|domain|agent.example.com"),
      identifier: { type: "domain", value: "agent.example.com" },
      cardUrl: card,
      status: "active",
      source: "claim",
      verification: {
        level: "verified-control",
        method: "dns-txt",
        lastVerifiedAt: verified,
        expiresAt: iso(new Date(Date.parse(verified) + 90 * DAY)),
        evidence: [{ kind: "dns-txt", ref: "_emissar-resolve-challenge.agent.example.com", checkedAt: verified }],
      },
      updatedAt: verified,
    },
    {
      id: recordId("claim|tel|+15195550142"),
      identifier: { type: "tel", value: "+15195550142" },
      cardUrl: card,
      status: "active",
      source: "claim",
      verification: {
        level: "verified-organization",
        method: "voice-otp",
        lastVerifiedAt: verified,
        expiresAt: iso(new Date(Date.parse(verified) + 90 * DAY)),
        evidence: [
          { kind: "voice-otp", checkedAt: verified },
          { kind: "card-listing", ref: card, checkedAt: verified },
          { kind: "business-registry", authority: "Corporations Canada", ref: "0000000-0", checkedAt: verified },
        ],
      },
      organization: org,
      updatedAt: verified,
    },
    {
      id: recordId("claim|brand|CA|exampletelecom"),
      identifier: { type: "brand", value: "exampletelecom", country: "CA", display: "Example Telecom" },
      cardUrl: card,
      status: "active",
      source: "claim",
      verification: {
        level: "verified-organization",
        method: "trademark-registration",
        lastVerifiedAt: verified,
        expiresAt: iso(new Date(Date.parse(verified) + 365 * DAY)),
        evidence: [
          { kind: "trademark-registration", authority: "CIPO", ref: "TMA000000", checkedAt: verified },
          { kind: "card-listing", ref: card, checkedAt: verified },
          { kind: "business-registry", authority: "Corporations Canada", ref: "0000000-0", checkedAt: verified },
        ],
      },
      organization: org,
      updatedAt: verified,
    },
  ];
}

// ---------------------------------------------------------------- section 8.6: rate limiting (fixed window per client)
class RateLimiter {
  constructor(limit, windowSeconds, name = "default") {
    Object.assign(this, { limit, windowSeconds, name, clients: new Map() });
  }
  take(client, now) {
    const t = Math.floor(now.getTime() / 1000);
    let w = this.clients.get(client);
    if (!w || t >= w.start + this.windowSeconds) w = { start: t - (t % this.windowSeconds), used: 0 };
    const reset = w.start + this.windowSeconds - t;
    const headers = {
      "RateLimit-Policy": `"${this.name}";q=${this.limit};w=${this.windowSeconds}`,
    };
    if (w.used >= this.limit) {
      this.clients.set(client, w);
      return { allowed: false, retryAfter: reset, headers: { ...headers, RateLimit: `"${this.name}";r=0;t=${reset}` } };
    }
    w.used++;
    this.clients.set(client, w);
    return { allowed: true, headers: { ...headers, RateLimit: `"${this.name}";r=${this.limit - w.used};t=${reset}` } };
  }
}

// ---------------------------------------------------------------- section 8: the lookup API
const COMMON = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Expose-Headers": "ETag, Retry-After, RateLimit, RateLimit-Policy",
  "X-Content-Type-Options": "nosniff",
};
const POSITIVE_MAX_AGE = 3600;
const NEGATIVE_MAX_AGE = 300;

class Registry {
  constructor(records, limiter) {
    this.limiter = limiter;
    this.index = new Map();
    for (const r of records) {
      const k = keyOf(r.identifier);
      const list = this.index.get(k) ?? [];
      // A claimed record supersedes an observed one for the same identifier (section 9.4).
      if (r.source === "claim") this.index.set(k, [...list.filter((x) => x.source !== "crawl"), r]);
      else if (!list.some((x) => x.source === "claim")) this.index.set(k, [...list, r]);
    }
  }

  /** Parse a request path into a normalized identifier, or an error. */
  parse(pathname) {
    const seg = pathname.split("/").slice(1).map((s) => {
      try {
        return decodeURIComponent(s);
      } catch {
        return null;
      }
    });
    if (seg[0] !== "v0" || seg.includes(null)) return { error: "unknown path" };
    let n;
    if (seg[1] === "tel" && seg.length === 3) n = normalizeTel(seg[2]);
    else if (seg[1] === "domain" && seg.length === 3) {
      n = normalizeDomain(seg[2]);
      if (n.ok && n.specialUse) n = fail("special-use names are never registered");
    } else if (seg[1] === "brand" && seg.length === 4) n = brandKey(seg[3], seg[2]);
    else return { error: "unknown path" };
    if (!n.ok) return { error: n.error, type: seg[1] };
    const canonical =
      n.type === "brand"
        ? `/v0/brand/${n.country}/${encodeURIComponent(n.value)}`
        : `/v0/${n.type}/${n.type === "tel" ? n.value : encodeURIComponent(n.value)}`;
    const query = { type: n.type, value: n.value };
    if (n.type === "brand") query.country = n.country;
    return { query, canonical };
  }

  handle({ method = "GET", path: pathname, headers = {}, client = "192.0.2.10" }, now = NOW) {
    if (method !== "GET" && method !== "HEAD") return { status: 405, headers: { ...COMMON, Allow: "GET, HEAD" }, body: null };
    const rl = this.limiter.take(client, now);
    if (!rl.allowed) {
      return this.#problem(429, "Too many lookups", `Retry after ${rl.retryAfter} seconds.`, null, {
        ...rl.headers,
        "Retry-After": String(rl.retryAfter),
        "Cache-Control": "no-store",
      });
    }
    const p = this.parse(pathname);
    if (p.error) return this.#problem(400, "Invalid identifier", p.error, null, { ...rl.headers, "Cache-Control": "public, max-age=3600" });
    if (p.canonical !== pathname) {
      return {
        status: 308,
        headers: { ...COMMON, ...rl.headers, Location: p.canonical, "Cache-Control": "public, max-age=86400" },
        body: null,
      };
    }
    const live = (this.index.get(keyOf(p.query)) ?? []).filter((r) => Date.parse(r.verification.expiresAt) > now.getTime());
    if (!live.length) {
      return this.#problem(404, "No record for this identifier", undefined, p.query, {
        ...rl.headers,
        "Cache-Control": `public, max-age=${NEGATIVE_MAX_AGE}`,
      });
    }
    const body = { resolve: "0.1", query: p.query, answer: "found", records: live };
    const etag = etagOf(body);
    const soonest = Math.min(...live.map((r) => Date.parse(r.verification.expiresAt)));
    const maxAge = Math.max(0, Math.min(POSITIVE_MAX_AGE, Math.floor((soonest - now.getTime()) / 1000)));
    const h = { ...COMMON, ...rl.headers, ETag: etag, "Cache-Control": `public, max-age=${maxAge}` };
    const inm = headers["If-None-Match"];
    if (inm && inm.split(",").map((s) => s.trim().replace(/^W\//, "")).some((t) => t === etag || t === "*")) {
      return { status: 304, headers: h, body: null };
    }
    return { status: 200, headers: { ...h, "Content-Type": "application/json" }, body: method === "HEAD" ? null : body };
  }

  #problem(status, title, detail, query, extra = {}) {
    const type = { 400: "invalid-identifier", 404: "not-found", 429: "rate-limited" }[status];
    const body = { type: `${PROBLEM_BASE}#${type}`, title, status, resolve: "0.1" };
    if (detail) body.detail = detail;
    if (status === 404) Object.assign(body, { answer: "not-found", query });
    return { status, headers: { ...COMMON, ...extra, "Content-Type": "application/problem+json" }, body };
  }
}

// ---------------------------------------------------------------- run
const log = JSON_MODE ? () => {} : (...a) => console.log(...a);
const show = (label, res) => {
  log(`\n> ${label}`);
  log(`< ${res.status}`);
  for (const [k, v] of Object.entries(res.headers)) if (!(k in COMMON)) log(`< ${k}: ${v}`);
  if (res.body) log(JSON.stringify(res.body, null, 2).replace(/^/gm, "  "));
};

log(`Emissar Resolve v0.1 example. Clock fixed at ${NOW.toISOString()}.`);

log("\n== 1. Normalization (section 5) ==");
const normCases = [
  ["tel", "+1 (519) 555-0142"],
  ["tel", "tel:+1-519-555-0142"],
  ["tel", "＋１ ８００ ５５５ ０１９９"],
  ["tel", "519-555-0142"],
  ["tel", "+1 800 FLOWERS"],
  ["tel", "+1 (019) 555-0142"],
  ["tel", "tel:+1-519-555-0142;ext=22"],
  ["tel", "+44 20 0000 0000 0000"],
  ["domain", "OpenSea.IO."],
  ["domain", "Bücher.example"],
  ["domain", "https://opensea.io/"],
  ["domain", "localhost"],
  ["domain", "-bad-.example.com"],
  ["brand", "EXAMPLE TELECOM, Inc.", "ca"],
  ["brand", "Example-Telecom Ltée", "CA"],
  ["brand", "Straße Co.", "DE"],
  ["brand", "Inc.", "US"],
];
const normalization = [];
for (const [type, input, country] of normCases) {
  const r = type === "tel" ? normalizeTel(input) : type === "domain" ? normalizeDomain(input) : brandKey(input, country);
  normalization.push({ type, input, country, result: r });
  const shown = r.ok
    ? `${r.value}${r.country ? ` (${r.country})` : ""}${r.kind ? ` [${r.kind}]` : ""}${r.display && r.type === "domain" ? ` display=${r.display}` : ""}${r.specialUse ? " [special-use]" : ""}`
    : `REJECT: ${r.error}`;
  log(`  ${type.padEnd(6)} ${JSON.stringify(input + (country ? ` / ${country}` : "")).padEnd(34)} -> ${shown}`);
}

log("\n== 2. Seeding observed records from the directory export (section 9) ==");
const { file, doc } = latestDirectoryExport();
log(`  source: ${file} (crawl ${doc.crawl.id}, status ${doc.crawl.status}, exported ${doc.exportedAt}, ${doc.entries.length} entries)`);
const seeds = [];
const seedLog = [];
for (const domain of SEED_DOMAINS) {
  const entry = doc.entries.find((e) => e.domain === domain);
  if (!entry) throw new Error(`${domain} is not in ${file}; pick three other entries`);
  const r = seedRecord(entry);
  seedLog.push({ domain, cardName: entry.name, providerOrganization: entry.provider?.organization ?? null, ...(r.skip ? { skip: r.skip } : { recordId: r.record.id }) });
  if (r.record) seeds.push(r.record);
  log(
    `  ${domain.padEnd(24)} card says name=${JSON.stringify(entry.name)}, organization=${JSON.stringify(entry.provider?.organization ?? null)}` +
      ` -> ${r.skip ? `skipped: ${r.skip}` : `observed record ${r.record.id}, card ${r.record.cardUrl}, expires ${r.record.verification.expiresAt}`}`,
  );
}
log("  (No tel or brand record is created from a card, and the card's self-described name and organization are not copied.)");

const claims = illustrativeClaims();
log("\n== 3. Illustrative claimed records (reserved example identifiers; not real claims) ==");
for (const c of claims) log(`  ${keyOf(c.identifier).padEnd(26)} ${c.verification.level} via ${c.verification.method} -> ${c.cardUrl}`);

const records = [...seeds, ...claims];
// Demo policy: 6 lookups per 60 s so the walkthrough reaches the limit; the spec's default is 60 per 60 s.
const registry = new Registry(records, new RateLimiter(6, 60));

log("\n== 4. Lookups (section 8) ==");
const responses = [];
const call = (label, req, now = NOW) => {
  const res = registry.handle(req, now);
  responses.push({ label, request: { path: req.path, headers: req.headers ?? {}, client: req.client ?? "192.0.2.10" }, ...res });
  show(`${req.method ?? "GET"} ${req.path}${req.headers ? " " + JSON.stringify(req.headers) : ""}  [${label}]`, res);
  return res;
};

const t0 = NOW;
const at = (s) => new Date(t0.getTime() + s * 1000);
call("non-canonical domain redirects", { path: "/v0/domain/OpenSea.IO" }, at(0));
const found = call("observed domain record", { path: "/v0/domain/opensea.io" }, at(1));
call("conditional request, unchanged", { path: "/v0/domain/opensea.io", headers: { "If-None-Match": found.headers.ETag } }, at(2));
call("tel lookup (illustrative claim)", { path: "/v0/tel/+15195550142" }, at(3));
call("brand lookup (illustrative claim)", { path: "/v0/brand/CA/exampletelecom" }, at(4));
call("negative answer", { path: "/v0/tel/+15195550199" }, at(5));
call("rate limit reached", { path: "/v0/domain/example.com" }, at(6));
call("another client is not limited: negative answer", { path: "/v0/domain/example.com", client: "198.51.100.7" }, at(7));
call("invalid identifier (national format)", { path: "/v0/tel/519-555-0142", client: "198.51.100.7" }, at(8));
call("after the window resets", { path: "/v0/domain/modelcontextprotocol.io" }, at(61));

const counts = responses.reduce((m, r) => ((m[r.status] = (m[r.status] ?? 0) + 1), m), {});
log(`\nSummary: ${normalization.length} normalization cases (${normalization.filter((n) => n.result.ok).length} accepted), ${seeds.length} observed + ${claims.length} illustrative records, ${responses.length} lookups: ${Object.entries(counts).map(([k, v]) => `${v}x${k}`).join(", ")}`);

if (JSON_MODE) {
  process.stdout.write(JSON.stringify({ now: NOW.toISOString(), source: { file, crawl: doc.crawl.id, exportedAt: doc.exportedAt }, normalization, seedLog, records, responses }, null, 2) + "\n");
}
