import { readFileSync } from "node:fs";
import { isAbsolute, join, resolve } from "node:path";

import {
  buildP0aRuntimeAssetPlan,
  defaultReplicationRoot,
  deployRuntimeAssetPlan,
  readRuntimeAssetManifest,
  serializeRuntimeAssetManifest,
} from "./lib/runtime-assets.mjs";

function option(name) {
  const index = process.argv.indexOf(name);
  return index >= 0 ? process.argv[index + 1] : undefined;
}

function defaultConfigPath() {
  if (!process.env.LOCALAPPDATA || !isAbsolute(process.env.LOCALAPPDATA)) throw new Error("local_app_data_unavailable");
  return join(process.env.LOCALAPPDATA, "Dada", "P0A", "config", "instance.json");
}

const configFile = resolve(option("--config") ?? process.env.DADA_INSTANCE_CONFIG_PATH ?? defaultConfigPath());
const configuration = JSON.parse(readFileSync(configFile, "utf8"));
const assetRootCandidate = option("--asset-root") ?? configuration.asset_root;
if (typeof assetRootCandidate !== "string" || !isAbsolute(assetRootCandidate)) {
  throw new Error("asset_root_configuration_invalid");
}
const assetRoot = resolve(assetRootCandidate);
const trustedManifest = readRuntimeAssetManifest(resolve(option("--trusted-manifest") ?? "config/runtime-assets-manifest.json"));
const plan = await buildP0aRuntimeAssetPlan({
  replicationRoot: resolve(option("--replication-root") ?? defaultReplicationRoot()),
});
if (serializeRuntimeAssetManifest(plan.manifest) !== serializeRuntimeAssetManifest(trustedManifest)) {
  throw new Error("runtime_asset_source_does_not_match_trusted_manifest");
}
const result = deployRuntimeAssetPlan({ assetRoot, manifest: trustedManifest, resources: plan.resources });
process.stdout.write(`${JSON.stringify({ linked_files: result.linked_files, status: result.status })}\n`);
