#!/usr/bin/env node

import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const scriptDir = dirname(fileURLToPath(import.meta.url));
const platformRoot = resolve(scriptDir, "../..");
const workspaceRoot = resolve(platformRoot, "..");
const foundryRoot = resolve(workspaceRoot, "NODEDC_DESIGN_GUIDELINE");
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"));
const [patchId = "module-foundry-zone-v2-consumer-policy-20260721-001", ...extra] = process.argv.slice(2);

if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
  throw new Error("patch_id_must_contain_only_letters_digits_dot_underscore_hyphen");
}

const files = [
  "registry/data-product-consumer-policies.json",
  "scripts/validate-registry.mjs",
  "server/foundry-data-product-consumer.mjs",
  "server/foundry-data-product-consumer.test.mjs",
];
const stage = await mkdtemp(join(tmpdir(), "nodedc-module-foundry-consumer-policy-artifact-"));
const payload = join(stage, "payload");
const artifact = join(artifactDir, `nodedc-module-foundry-${patchId}.tgz`);
const checksum = `${artifact}.sha256`;

await assertConsumerPolicyBoundary();

try {
  await mkdir(payload, { recursive: true });
  for (const relativePath of files) {
    const source = resolve(foundryRoot, relativePath);
    const sourceStat = await lstat(source);
    if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
      throw new Error(`source_file_rejected:${relativePath}`);
    }
    const destination = join(payload, relativePath);
    await mkdir(dirname(destination), { recursive: true });
    await cp(source, destination, { force: true, verbatimSymlinks: true });
  }

  await writeFile(join(stage, "manifest.env"), `id=${patchId}\ncomponent=module-foundry\ntype=app-overlay\n`, "utf8");
  await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
  await mkdir(artifactDir, { recursive: true });

  const tar = spawnSync("python3", ["-c", canonicalTarScript(), artifact, stage], {
    encoding: "utf8",
    maxBuffer: 32 * 1024 * 1024,
  });
  if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);

  const sha256 = createHash("sha256").update(await readFile(artifact)).digest("hex");
  await writeFile(checksum, `${sha256}  ${artifact.split("/").at(-1)}\n`, "utf8");
  console.log(JSON.stringify({ ok: true, patchId, artifact, checksum, sha256, files }, null, 2));
} finally {
  await rm(stage, { recursive: true, force: true });
}

async function assertConsumerPolicyBoundary() {
  const registry = JSON.parse(await readFile(resolve(foundryRoot, files[0]), "utf8"));
  if (registry?.schemaVersion !== "nodedc.foundry.data-product-consumer-policies/v1") {
    throw new Error("foundry_consumer_policy_registry_invalid");
  }
  const movingObjectV4Matches = registry.policies?.filter((policy) => (
    policy?.dataProductId === "fleet.positions.current.v4" && policy?.productVersion === "4.0.0"
  )) || [];
  if (movingObjectV4Matches.length !== 1) throw new Error("foundry_consumer_policy_v4_missing_or_ambiguous");
  const movingObjectV4Policy = movingObjectV4Matches[0];
  if (
    movingObjectV4Policy.id !== "map-moving-object-current-v4"
    || movingObjectV4Policy.version !== "4.0.0"
    || movingObjectV4Policy.staleAfterMs !== null
    || movingObjectV4Policy.statusContract?.attribute !== "signal_state"
    || JSON.stringify(movingObjectV4Policy.statusContract?.allowedValues) !== JSON.stringify(["active", "inactive"])
    || movingObjectV4Policy.statusContract?.missing !== "reject"
    || movingObjectV4Policy.statusContract?.freshness !== "none"
    || JSON.stringify(movingObjectV4Policy.terminalStatuses) !== JSON.stringify(["inactive"])
    || movingObjectV4Policy.removeMode !== "canonical-tombstone-or-snapshot-rebase"
  ) throw new Error("foundry_consumer_policy_v4_contract_invalid");

  const zoneV1Matches = registry.policies?.filter((policy) => (
    policy?.dataProductId === "map.zones.current.v1" && policy?.productVersion === "1.0.0"
  )) || [];
  if (zoneV1Matches.length !== 1 || JSON.stringify(zoneV1Matches[0]) !== JSON.stringify({
    id: "map-zone-current-v1",
    version: "1.0.0",
    dataProductId: "map.zones.current.v1",
    productVersion: "1.0.0",
    freshness: "none",
    staleAfterMs: null,
    terminalStatuses: [],
    removeMode: "canonical-tombstone-or-snapshot-rebase",
  })) throw new Error("foundry_consumer_policy_zone_v1_contract_changed");

  const zoneV2Matches = registry.policies?.filter((policy) => (
    policy?.dataProductId === "map.zones.current.v2" && policy?.productVersion === "2.0.0"
  )) || [];
  if (zoneV2Matches.length !== 1) throw new Error("foundry_consumer_policy_zone_v2_missing_or_ambiguous");
  const zoneV2Policy = zoneV2Matches[0];
  const expectedProjection = [
    "display_name",
    "geometry_kind",
    "max_speed_kph",
    "schedule_timezone",
    "applies_to_couriers",
    "applies_to_kicksharing",
  ];
  if (
    zoneV2Policy.id !== "map-zone-current-v2"
    || zoneV2Policy.version !== "2.0.0"
    || zoneV2Policy.freshness !== "none"
    || zoneV2Policy.staleAfterMs !== null
    || JSON.stringify(zoneV2Policy.terminalStatuses) !== JSON.stringify([])
    || zoneV2Policy.consumerContract?.ontologyRevision !== "ontology.map.zone.v1"
    || zoneV2Policy.consumerContract?.deliveryMode !== "snapshot+patch"
    || JSON.stringify(zoneV2Policy.consumerContract?.semanticTypes) !== JSON.stringify(["map.zone"])
    || JSON.stringify(zoneV2Policy.consumerContract?.fieldProjection) !== JSON.stringify(expectedProjection)
    || JSON.stringify(zoneV2Policy.consumerContract?.geometryTypes) !== JSON.stringify(["Polygon", "MultiPolygon"])
    || zoneV2Policy.consumerContract?.subjectIdentity !== "semantic-type+source-id"
    || zoneV2Policy.consumerContract?.snapshotMode !== "atomic-replace"
    || zoneV2Policy.consumerContract?.patchMode !== "atomic"
    || zoneV2Policy.removeMode !== "canonical-tombstone-or-snapshot-rebase"
  ) throw new Error("foundry_consumer_policy_zone_v2_contract_invalid");

  const unitProfileV1Matches = registry.policies?.filter((policy) => (
    policy?.dataProductId === "fleet.units.profile.current.v1" && policy?.productVersion === "1.0.0"
  )) || [];
  if (unitProfileV1Matches.length !== 1) throw new Error("foundry_consumer_policy_unit_profile_v1_missing_or_ambiguous");
  const unitProfileV1Policy = unitProfileV1Matches[0];
  const expectedUnitProfileProjection = [
    "corrected_engine_hours_factor",
    "corrected_mileage_factor",
    "display_name",
    "filter_by_satellite_count_enabled",
    "filter_by_satellite_count_value",
    "filter_emissions",
    "hardware_manufacturer_name",
    "hardware_port",
    "hardware_type_class",
    "hardware_type_name",
    "limit_acceleration",
    "lost_connection_enabled",
    "lost_connection_time_value",
    "maximum_permissible_speed",
    "maximum_valid_height",
    "maximum_valid_speed",
    "mileage_by_ignition",
    "minimum_movement_speed",
    "minimum_movement_time",
    "minimum_parking_time",
    "minimum_stop_time",
    "minimum_trip_distance",
    "minimum_valid_height",
    "speed_parameter",
    "trip_detection_type",
    "unit_type_class",
    "unit_type_name",
    "use_odometer",
  ];
  if (
    unitProfileV1Policy.id !== "map-moving-object-unit-profile-current-v1"
    || unitProfileV1Policy.version !== "1.0.0"
    || unitProfileV1Policy.freshness !== "none"
    || unitProfileV1Policy.staleAfterMs !== null
    || JSON.stringify(unitProfileV1Policy.terminalStatuses) !== JSON.stringify([])
    || unitProfileV1Policy.consumerContract?.ontologyRevision !== "ontology.map.moving_object.v3"
    || unitProfileV1Policy.consumerContract?.deliveryMode !== "snapshot+patch"
    || JSON.stringify(unitProfileV1Policy.consumerContract?.semanticTypes) !== JSON.stringify(["map.moving_object"])
    || JSON.stringify(unitProfileV1Policy.consumerContract?.fieldProjection) !== JSON.stringify(expectedUnitProfileProjection)
    || JSON.stringify(unitProfileV1Policy.consumerContract?.geometryTypes) !== JSON.stringify([])
    || unitProfileV1Policy.consumerContract?.subjectIdentity !== "semantic-type+source-id"
    || unitProfileV1Policy.consumerContract?.snapshotMode !== "atomic-replace"
    || unitProfileV1Policy.consumerContract?.patchMode !== "atomic"
    || unitProfileV1Policy.removeMode !== "canonical-tombstone-or-snapshot-rebase"
  ) throw new Error("foundry_consumer_policy_unit_profile_v1_contract_invalid");

  for (const [id, policy] of [
    ["v4", movingObjectV4Policy],
    ["zone-v2", zoneV2Policy],
    ["unit-profile-v1", unitProfileV1Policy],
  ]) {
    const allowedPolicyKeys = new Set([
      "id",
      "version",
      "dataProductId",
      "productVersion",
      "freshness",
      "staleAfterMs",
      "terminalStatuses",
      "statusContract",
      "consumerContract",
      "removeMode",
    ]);
    if (
      Object.keys(policy).some((key) => !allowedPolicyKeys.has(key))
      || /(provider|tenant|endpoint|credential|token|secret|authorization)/i.test(JSON.stringify(policy))
    ) {
      throw new Error(`foundry_consumer_policy_${id}_transport_boundary_violation`);
    }
  }

  const consumer = await readFile(resolve(foundryRoot, files[2]), "utf8");
  for (const marker of [
    "data_product_consumer_fact_status_invalid",
    "data_product_consumer_status_field_not_projected",
    'policy.freshness === "none"',
    "assertConsumerContract(policy.consumerContract, product, target.binding)",
    "data_product_snapshot_product_mismatch",
    "data_product_patch_product_mismatch",
    "data_product_consumer_fact_contract_invalid",
  ]) {
    if (!consumer.includes(marker)) throw new Error(`foundry_consumer_policy_runtime_guard_missing:${marker}`);
  }
}

function canonicalTarScript() {
  return [
    "import gzip,io,pathlib,sys,tarfile",
    "root=pathlib.Path(sys.argv[2])",
    "with open(sys.argv[1],'wb') as out:",
    " with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
    "  with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
    "   for top in ('manifest.env','files.txt','payload'):",
    "    p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
    "    for x in paths:",
    "     info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
    "     info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
    "     with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
  ].join("\n");
}
