#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
import { ConfigurationAuthorityService } from "@awp/application";
import {
  authorityContext,
  unsafeOpaqueId,
  type AwpId,
  type CorrelationId,
  type OperationId,
  type PrincipalId,
} from "@awp/contracts";
import { createPostgresRuntime } from "@awp/persistence";

function requiredEnvironment(name: string): string {
  const value = process.env[name]?.trim();
  if (!value) throw new Error(`${name} is required`);
  return value;
}

function booleanEnvironment(name: string): boolean {
  const value = requiredEnvironment(name);
  if (value === "1" || value === "true") return true;
  if (value === "0" || value === "false") return false;
  throw new Error(`${name} must be exactly 0, 1, false, or true`);
}

const databaseUrl = requiredEnvironment("DATABASE_URL");
const nativeAcpEnabled = booleanEnvironment("AWP_CONFIG_NATIVE_ACP_ENABLED");
const namespace = requiredEnvironment("AWP_CONFIG_WORKSPACE_NAMESPACE");
const image = requiredEnvironment("AWP_CONFIG_WORKSPACE_IMAGE");
const migrationsFolder = fileURLToPath(
  new URL("../../../packages/persistence/drizzle/", import.meta.url),
);
const runtime = createPostgresRuntime(databaseUrl, migrationsFolder);
const clock = { now: () => new Date() };
const ids = {
  next<T extends AwpId>(): T {
    return unsafeOpaqueId<T>(randomUUID());
  },
};
const principal = {
  id: unsafeOpaqueId<PrincipalId>("principal:system:dogfood-deployment"),
  kind: "system" as const,
  capabilities: [],
};
const operationId = unsafeOpaqueId<OperationId>(`operation:${randomUUID()}`);
const correlationId = unsafeOpaqueId<CorrelationId>(`correlation:${randomUUID()}`);
const context = {
  operationId,
  correlationId,
  idempotencyKey: operationId,
  authority: authorityContext(principal, []),
};

try {
  await runtime.migrate();
  const configuration = new ConfigurationAuthorityService(runtime.uow, ids, clock);
  await configuration.ensureDefinitions();
  const imported = await Promise.all([
    configuration.importDeploymentSystemValue(
      "execution.nativeAcpEnabled",
      nativeAcpEnabled,
      context,
    ),
    configuration.importDeploymentSystemValue("workspace.namespace", namespace, context),
    configuration.importDeploymentSystemValue("workspace.image", image, context),
  ]);
  const effective = await configuration.resolveSystemWorkspaceConfiguration();
  if (
    effective.nativeAcpEnabled !== nativeAcpEnabled ||
    effective.namespace !== namespace ||
    effective.image !== image
  ) {
    throw new Error("Imported I1 deployment configuration did not resolve to the requested values");
  }
  process.stdout.write(
    `${imported.map((item) => `${item.definitionKey}@r${item.resourceRevision}`).join(" ")}\n`,
  );
} finally {
  await runtime.close();
}
