import { resolve } from "node:path";

const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

export const PRODUCTION_RESOURCES = Object.freeze({
  worker: "hearbooks-reader",
  database: "hearbooks-reader-db",
  bucket: "hearbooks-reader-storage",
});

export function wranglerInvocation({ execPath, projectDirectory, arguments_ }) {
  return {
    command: execPath,
    arguments: [
      resolve(projectDirectory, "node_modules", "wrangler", "bin", "wrangler.js"),
      ...arguments_,
    ],
  };
}

function parseBucketNames(r2Text) {
  const trimmed = r2Text.trim();
  if (trimmed.startsWith("[")) {
    const buckets = JSON.parse(trimmed);
    return buckets.map((bucket) => bucket.name);
  }

  return [...r2Text.matchAll(/^name:\s+(.+?)\s*$/gm)].map((match) => match[1]);
}

export function resolveProductionInventory({ d1Json, r2Text }) {
  const databases = JSON.parse(d1Json);
  const databaseMatches = databases.filter(
    (database) => database.name === PRODUCTION_RESOURCES.database,
  );

  if (
    databaseMatches.length !== 1
    || !UUID_PATTERN.test(databaseMatches[0]?.uuid ?? "")
  ) {
    throw new Error(
      `Expected exactly one ${PRODUCTION_RESOURCES.database} with a valid UUID.`,
    );
  }

  const bucketMatches = parseBucketNames(r2Text).filter(
    (name) => name === PRODUCTION_RESOURCES.bucket,
  );
  if (bucketMatches.length !== 1) {
    throw new Error(`Expected exactly one ${PRODUCTION_RESOURCES.bucket}.`);
  }

  return { databaseId: databaseMatches[0].uuid };
}

export function buildProductionConfig({ databaseId }) {
  if (!UUID_PATTERN.test(databaseId)) {
    throw new Error("A valid HearBooks D1 UUID is required.");
  }

  return {
    $schema: "node_modules/wrangler/config-schema.json",
    name: PRODUCTION_RESOURCES.worker,
    main: "./dist/server/index.js",
    compatibility_date: "2026-08-28",
    compatibility_flags: ["nodejs_compat"],
    workers_dev: true,
    no_bundle: true,
    assets: { directory: "./dist/client" },
    rules: [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }],
    d1_databases: [{
      binding: "DB",
      database_name: PRODUCTION_RESOURCES.database,
      database_id: databaseId,
      migrations_dir: "./drizzle",
    }],
    r2_buckets: [{
      binding: "STORAGE",
      bucket_name: PRODUCTION_RESOURCES.bucket,
    }],
    observability: { enabled: true },
  };
}
