#!/usr/bin/env node

/**
 * Blue Jetty pilot onboarding CLI. Requires Node.js 22+ and no dependencies.
 * The API key is read only from BLUEJETTY_API_KEY and is never printed.
 */

import { randomUUID } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";
import { pathToFileURL } from "node:url";

function parseArgs(argv) {
  const options = {
    baseUrl: process.env.BLUEJETTY_BASE_URL ?? "https://bluejetty.ai",
    inputPath: null,
    outputPath: "bluejetty-submission.json",
    json: false,
    submit: false,
    yes: false,
    expectedVersion: null
  };
  for (let index = 0; index < argv.length; index += 1) {
    const argument = argv[index];
    if (argument === "--base-url") options.baseUrl = argv[++index];
    else if (argument === "--input") options.inputPath = argv[++index];
    else if (argument === "--out") options.outputPath = argv[++index];
    else if (argument === "--json") options.json = true;
    else if (argument === "--submit") options.submit = true;
    else if (argument === "--yes") options.yes = true;
    else if (argument === "--expected-version") { options.expectedVersion = Number(argv[++index]); if (!Number.isSafeInteger(options.expectedVersion) || options.expectedVersion < 0) throw new Error("--expected-version requires a nonnegative integer from the owner publication API"); }
    else if (argument === "--help" || argument === "-h") options.help = true;
    else throw new Error(`Unknown argument: ${argument}`);
  }
  if (!options.baseUrl || !URL.canParse(options.baseUrl)) throw new Error("--base-url must be an absolute URL");
  options.baseUrl = new URL(options.baseUrl).origin;
  return options;
}

function usage() {
  return `Blue Jetty pilot onboarding CLI

Interactive draft:
  node bluejetty-onboard.mjs

Coding-agent mode:
  node bluejetty-onboard.mjs --input onboarding-input.json --json

Before running changes, explain the task and environment-specific concerns to the user.
Show the exact proposed public content, visibility and destinations. Obtain explicit human
confirmation of accuracy, publication rights and the level of detail and fidelity they
are comfortable exposing to crawlers and anyone on the open web. Public copies may persist.
Never infer consent from receiving a prompt or API key. Use --yes only after this approval.

Validate and submit after explicit authorization:
  node bluejetty-onboard.mjs --input onboarding-input.json --json --submit --yes

Environment:
  BLUEJETTY_API_KEY   Required one-time-display bearer key
  BLUEJETTY_BASE_URL  Optional API origin (defaults to https://bluejetty.ai)

Input format:
  {"app":{"name":"...","developerName":"...","publisherDomain":"...","publisherWebsiteUrl":"https://.../","iosBundleId":"..."},"discovery":{"sitemapUrl":"https://.../sitemap.xml","maxPages":10}}
  You may provide "records" instead of "discovery" when you already have profile-0.1 entities.

Start with a compact map of real experiences and destinations, not a database export.
Useful richer metadata is welcome. Keep private/end-user data out.
Full snapshots tombstone omitted records: review deletions before updating an existing source.
Existing-app updates require --expected-version N from GET /v1/apps/{appId}/publication.
Review its current assertions first; reconcile a 412 conflict before retrying.
Guide and examples: https://bluejetty.ai/developers/app-mapping.md`;
}

async function apiRequest(baseUrl, apiKey, path, body, headers = {}) {
  const response = await fetch(`${baseUrl}${path}`, {
    method: "POST",
    headers: {
      accept: "application/json",
      authorization: `Bearer ${apiKey}`,
      "content-type": "application/json",
      ...headers
    },
    body: JSON.stringify(body)
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    const code = payload?.error?.code ?? `HTTP_${response.status}`;
    const message = payload?.error?.message ?? "Request failed";
    const details = payload?.error?.details ? ` ${JSON.stringify(payload.error.details)}` : "";
    throw new Error(`${code}: ${message}${details}`);
  }
  return { status: response.status, payload };
}

async function interactiveInput() {
  const terminal = createInterface({ input, output });
  try {
    const name = await terminal.question("App name: ");
    const developerName = await terminal.question("Developer/company name: ");
    const publisherDomain = await terminal.question("Publisher domain (example.com): ");
    const publisherWebsiteUrl = await terminal.question("Canonical HTTPS publisher website: ");
    const iosBundleId = await terminal.question("iOS bundle ID (leave blank if Android-only): ");
    const androidPackageName = await terminal.question("Android package name (leave blank if iOS-only): ");
    const sitemapUrl = await terminal.question("HTTPS sitemap URL: ");
    return {
      app: {
        name,
        developerName,
        publisherDomain,
        publisherWebsiteUrl,
        ...(iosBundleId ? { iosBundleId } : {}),
        ...(androidPackageName ? { androidPackageName } : {})
      },
      discovery: { sitemapUrl, maxPages: 10 }
    };
  } finally {
    terminal.close();
  }
}

async function confirmSubmission() {
  const terminal = createInterface({ input, output });
  try {
    return (await terminal.question("Have you reviewed this app map and approved its accuracy, publication rights, destinations, and level of detail and fidelity for crawlers and anyone on the open web? Public copies may persist after removal. Submit now? Type yes: ")).trim().toLowerCase() === "yes";
  } finally {
    terminal.close();
  }
}

export async function onboard(options, dependencies = {}) {
  const apiKey = dependencies.apiKey ?? process.env.BLUEJETTY_API_KEY;
  if (!apiKey) throw new Error("Set BLUEJETTY_API_KEY to the key created in your Blue Jetty account");
  const readInput = dependencies.readInput ?? (options.inputPath
    ? async () => JSON.parse(await readFile(options.inputPath, "utf8"))
    : interactiveInput);
  const onboardingInput = await readInput();
  const previewResponse = await apiRequest(options.baseUrl, apiKey, "/v1/onboarding/preview", onboardingInput);
  const submission = previewResponse.payload.data.submission;
  await (dependencies.writeOutput ?? writeFile)(options.outputPath, `${JSON.stringify(submission, null, 2)}\n`, "utf8");
  const validationResponse = await apiRequest(options.baseUrl, apiKey, "/v1/validate", submission);

  const result = {
    valid: validationResponse.payload.data.valid,
    mutationPerformed: false,
    outputPath: options.outputPath,
    app: validationResponse.payload.data.app,
    snapshot: validationResponse.payload.data.snapshot,
    discovery: previewResponse.payload.data.discovery,
    submission: null
  };

  if (options.submit) {
    if (!result.valid) throw new Error("Fix every rejected record before submitting a full snapshot");
    const approved = options.yes || (!options.json && await (dependencies.confirm ?? confirmSubmission)());
    if (!approved) throw new Error("Submission was not authorized; the validated draft was saved without mutation");
    const idempotencyKey = `onboard-${randomUUID()}`;
    const submitted = await apiRequest(options.baseUrl, apiKey, "/v1/submissions", submission, {
      "idempotency-key": idempotencyKey,
      ...(options.expectedVersion == null ? {} : { "if-match": `"bj-publication-${options.expectedVersion}"` })
    });
    result.mutationPerformed = true;
    result.submission = submitted.payload.data;
  }

  return result;
}

async function main() {
  const options = parseArgs(process.argv.slice(2));
  if (options.help) {
    console.log(usage());
    return;
  }
  if (options.json && !options.inputPath) throw new Error("--json requires --input so coding-agent runs are deterministic");
  if (options.submit && options.json && !options.yes) {
    throw new Error("Non-interactive submission requires both --submit and --yes");
  }

  const result = await onboard(options);
  if (options.json) console.log(JSON.stringify(result));
  else {
    console.log(`\nValidated ${result.snapshot?.acceptedCount ?? 0} records for ${result.app.name}.`);
    console.log(`Draft saved to ${result.outputPath}. No data was submitted${result.mutationPerformed ? " until the authorized final step" : ""}.`);
    if (result.submission) console.log(`Onboarding status: ${result.submission.urls.status}`);
    else console.log("Review the draft, then rerun with --submit when you are ready.");
  }
}

const invokedPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
if (import.meta.url === invokedPath) {
  main().catch((error) => {
    console.error(error instanceof Error ? error.message : error);
    process.exitCode = 1;
  });
}
