#!/usr/bin/env node
import { realpath, stat } from "node:fs/promises";
import { PrismaClient } from "@prisma/client";
import { verifyStoredFeishuApplicationEnvelopes } from "../connections/feishuApplicationConnections.js";
import { verifyStoredProviderEnvelopes } from "../connections/providerConnections.js";
import { loadLocalSecretKeyringFile, LocalSecretEnvelope } from "../security/secretEnvelope.js";
import { readSiloOrganizationId, requireSiloOrganization } from "./silo.js";

async function main(): Promise<void> {
  const keyringFile = parseArgs(process.argv.slice(2));
  const databaseUrl = process.env["DATABASE_URL"]?.trim();
  const workspaceRoot = process.env["HUB_PROJECT_WORKSPACE_ROOT"]?.trim();
  if (databaseUrl === undefined || databaseUrl === "") throw new Error("DATABASE_URL is required");
  if (workspaceRoot === undefined || workspaceRoot === "") throw new Error("HUB_PROJECT_WORKSPACE_ROOT is required");
  const workspace = await realpath(workspaceRoot);
  if (!(await stat(workspace)).isDirectory()) throw new Error("restored workspace root is not a directory");
  const secrets = new LocalSecretEnvelope(await loadLocalSecretKeyringFile(keyringFile));
  const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } }, log: [] });
  try {
    const organization = await requireSiloOrganization(prisma, readSiloOrganizationId());
    const provider = await verifyStoredProviderEnvelopes(prisma, secrets);
    const feishu = await verifyStoredFeishuApplicationEnvelopes(prisma, secrets);
    const [activeProviders, activeFeishu] = await Promise.all([
      prisma.organizationProviderConnection.count({
        where: { organizationId: organization.id, status: "ACTIVE", activeSecretVersionId: { not: null } },
      }),
      prisma.organizationFeishuApplicationConnection.count({
        where: { organizationId: organization.id, status: "ACTIVE", activeSecretVersionId: { not: null } },
      }),
    ]);
    if (activeProviders < 1) throw new Error("restored Silo has no ACTIVE Provider Connection");
    if (activeFeishu !== 1) throw new Error(`restored Silo must have one ACTIVE Feishu Connection; found ${activeFeishu}`);
    console.log(JSON.stringify({ organizationId: organization.id, providerEnvelopes: provider, feishuEnvelopes: feishu }));
  } finally {
    await prisma.$disconnect();
  }
}

function parseArgs(argv: readonly string[]): string {
  if (argv.length !== 2 || argv[0] !== "--keyring-file" || argv[1] === undefined || argv[1] === "") {
    throw new Error("usage: restore-preflight --keyring-file /root/recovery/secret-keyring.json");
  }
  return argv[1];
}

main().catch((error: unknown) => {
  console.error(`[restore-preflight] failed: ${error instanceof Error ? error.message : String(error)}`);
  process.exitCode = 1;
});
