export interface LidarDistribution {
  sampleCount: number;
  minimum: number | null;
  mean: number | null;
  p50: number | null;
  p95: number | null;
  maximum: number | null;
}

export interface LidarPackSummary {
  packId: string;
  sessionId: string;
  profileId: string;
  pointFrames: number;
  poseFrames: number;
  points: number;
  meanPointsPerFrame: number | null;
  p95FrameIntervalMs: number | null;
  poseCoverageFraction: number | null;
  equivalenceStatus: "passed";
  logicalContentSha256: string;
  createdAtUtc: string | null;
}

export interface LidarReplayCatalog {
  configured: boolean;
  validTotal: number;
  invalidTotal: number;
  duplicateTotal: number;
  items: LidarPackSummary[];
}

export interface LidarStageReadiness {
  stage: string;
  readiness: "ready" | "degraded" | "blocked";
  reasons: string[];
}

export interface LidarReplayDetail {
  pack: LidarPackSummary;
  quality: {
    fieldRetention: Record<string, boolean>;
    pointCountPerFrame: LidarDistribution;
    pointFrameIntervalMs: LidarDistribution;
    intensity: LidarDistribution;
    poseBinding: {
      thresholdMs: number;
      coveredPointFrames: number;
      coverageFraction: number;
      nearestDeltaMs: LidarDistribution;
    };
    limitations: string[];
  };
  equivalence: {
    status: "passed";
    arraysCompared: number;
    arrayMismatches: number;
  };
  stages: LidarStageReadiness[];
}

export interface LidarGroundProviderSummary {
  providerId: string;
  sourceCommit: string | null;
}

export interface LidarGroundBenchmark {
  benchmarkId: string;
  replayPackId: string;
  sessionId: string;
  status: "diagnostic-only";
  frames: number;
  points: number;
  inputDomain: {
    accepted: false;
    representation: string;
    physicalSensorHeightKnown: boolean;
    sensorScanGeometryKnown: boolean;
    reason: string;
    normalization: {
      sensorHeightM: number;
      mapVerticalOriginOffsetM: number;
      heightEvidence: "missing" | "operator-estimated" | "runtime-calibrated";
    } | null;
  };
  labels: {
    status: "missing-independent-review";
    metricsAvailable: false;
  };
  current: {
    provider: LidarGroundProviderSummary;
    groundFraction: LidarDistribution;
    assignedFraction: LidarDistribution;
    latencyMs: LidarDistribution;
  };
  candidate: {
    provider: LidarGroundProviderSummary;
    groundFraction: LidarDistribution;
    assignedFraction: LidarDistribution;
    latencyMs: LidarDistribution;
  };
  comparison: {
    algorithmGroundIou: LidarDistribution;
    groundDisagreementFraction: LidarDistribution;
    isAccuracyMetric: false;
  };
  decision: {
    status: "do-not-promote-on-current-vendor-map";
    productionPromotion: false;
    reasons: string[];
    nextGate: string;
  };
  createdAtUtc: string | null;
}

export interface LidarGroundBenchmarkCatalog {
  configured: boolean;
  validTotal: number;
  invalidTotal: number;
  items: LidarGroundBenchmark[];
}

export interface LidarGroundFrame {
  benchmarkId: string;
  replayPackId: string;
  sessionId: string;
  frameIndex: number;
  frameCount: number;
  captureSequence: number;
  pointCount: number;
  coordinateFrame: "map";
  distanceUnit: "m";
  pointsXyzM: Array<[number, number, number]>;
  intensity0To255: number[];
  masks: {
    currentGround: number[];
    currentAssigned: number[];
    candidateGround: number[];
    candidateAssigned: number[];
    disagreement: number[];
  };
  counts: {
    currentGround: number;
    candidateGround: number;
    disagreement: number;
  };
  groundTruth: false;
}

export interface LidarFieldReviewWindowSummary {
  index: number;
  key: string;
  label: string;
  startSeconds: number;
  endSeconds: number;
  midpointSeconds: number;
  sourceLidarSamples: number;
  sourcePointCount: number;
  displayPointCount: number;
  sourceFrameStart: number;
  sourceFrameEnd: number;
  previewSourceFrameIndex: number;
  previewSessionSeconds: number;
}

export interface LidarFieldReview {
  reviewId: string;
  displayName: string;
  sessionId: string;
  sourcePackId: string;
  status: "diagnostic-only";
  source: {
    timelineStartSeconds: number;
    timelineEndSeconds: number;
    availableLidarFrames: number;
    pointCount: number;
    representation: "legacy-e10-vendor-map-with-pose";
    intensityAvailable: false;
    rawScanAccepted: false;
  };
  selection: {
    purpose: "operator-readable-central-urban-field-review";
    defaultWindowIndex: number;
    accumulation: "per-source-frame masks accumulated in map frame";
    maximumPointsPerWindow: number;
  };
  windows: LidarFieldReviewWindowSummary[];
  metrics: {
    sourceSamples: number;
    current: {
      provider: LidarGroundProviderSummary;
      groundFraction: LidarDistribution;
      latencyMs: LidarDistribution;
    };
    candidate: {
      provider: LidarGroundProviderSummary;
      groundFraction: LidarDistribution;
      latencyMs: LidarDistribution;
    };
    comparison: {
      algorithmGroundIou: LidarDistribution;
      groundDisagreementFraction: LidarDistribution;
      isAccuracyMetric: false;
    };
  };
  decision: {
    status: "visual-review-only";
    productionPromotion: false;
    reasons: string[];
  };
  createdAtUtc: string | null;
  groundTruth: false;
  authority: {
    commandsEnabled: false;
    navigationOrSafetyAccepted: false;
  };
}

export interface LidarFieldReviewCatalog {
  configured: boolean;
  validTotal: number;
  invalidTotal: number;
  items: LidarFieldReview[];
}

export interface LidarFieldReviewWindow {
  reviewId: string;
  displayName: string;
  sessionId: string;
  sourcePackId: string;
  windowIndex: number;
  windowCount: number;
  window: LidarFieldReviewWindowSummary;
  pointCount: number;
  coordinateFrame: "map";
  distanceUnit: "m";
  pointsXyzM: Array<[number, number, number]>;
  intensity0To255: null;
  intensity: {
    available: false;
    reason: string;
  };
  masks: LidarGroundFrame["masks"];
  counts: LidarGroundFrame["counts"];
  previewUrl: string;
  groundTruth: false;
  authority: LidarFieldReview["authority"];
}

export class LidarReplayContractError extends Error {}

export class LidarReplayApiError extends Error {
  constructor(message: string, readonly status: number | null = null) {
    super(message);
  }
}

type LidarFetch = (
  input: RequestInfo | URL,
  init?: RequestInit,
) => Promise<Response>;

const SAFE_PACK_ID = /^lidar-replay-pack-[a-f0-9]{64}$/;
const SAFE_GROUND_BENCHMARK_ID = /^ground-benchmark-[a-f0-9]{64}$/;
const SAFE_FIELD_REVIEW_ID = /^lidar-field-review-[a-f0-9]{64}$/;
const SAFE_E10_PACK_ID = /^e10-lidar-pack-[a-f0-9]{64}$/;
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$/;
const SAFE_FIELD_KEY = /^[a-z0-9][a-z0-9-]{0,63}$/;
const SHA256 = /^[a-f0-9]{64}$/;
const GIT_SHA1 = /^[a-f0-9]{40}$/;

function record(value: unknown, label: string): Record<string, unknown> {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new LidarReplayContractError(`${label}: ожидался объект`);
  }
  return value as Record<string, unknown>;
}

function array(value: unknown, label: string): unknown[] {
  if (!Array.isArray(value)) {
    throw new LidarReplayContractError(`${label}: ожидался массив`);
  }
  return value;
}

function string(value: unknown, label: string, pattern?: RegExp): string {
  if (typeof value !== "string" || !value || (pattern && !pattern.test(value))) {
    throw new LidarReplayContractError(`${label}: некорректная строка`);
  }
  return value;
}

function number(value: unknown, label: string, nullable = false): number | null {
  if (nullable && value === null) return null;
  if (typeof value !== "number" || !Number.isFinite(value)) {
    throw new LidarReplayContractError(`${label}: некорректное число`);
  }
  return value;
}

function integer(value: unknown, label: string): number {
  const parsed = number(value, label);
  if (parsed === null || !Number.isInteger(parsed) || parsed < 0) {
    throw new LidarReplayContractError(`${label}: ожидалось неотрицательное целое`);
  }
  return parsed;
}

function boolean(value: unknown, label: string): boolean {
  if (typeof value !== "boolean") {
    throw new LidarReplayContractError(`${label}: ожидался boolean`);
  }
  return value;
}

function groundMask(value: unknown, label: string, count: number): number[] {
  const values = array(value, label);
  if (values.length !== count) {
    throw new LidarReplayContractError(`${label}: длина маски не совпадает`);
  }
  return values.map((item, index) => {
    const parsed = integer(item, `${label}[${index}]`);
    if (parsed !== 0 && parsed !== 1) {
      throw new LidarReplayContractError(`${label}: ожидалась бинарная маска`);
    }
    return parsed;
  });
}

function distribution(value: unknown, label: string): LidarDistribution {
  const source = record(value, label);
  return {
    sampleCount: integer(source.sample_count, `${label}.sample_count`),
    minimum: number(source.minimum, `${label}.minimum`, true),
    mean: number(source.mean, `${label}.mean`, true),
    p50: number(source.p50, `${label}.p50`, true),
    p95: number(source.p95, `${label}.p95`, true),
    maximum: number(source.maximum, `${label}.maximum`, true),
  };
}

function packSummary(value: unknown): LidarPackSummary {
  const source = record(value, "LiDAR pack");
  if (source.equivalence_status !== "passed") {
    throw new LidarReplayContractError("LiDAR pack не прошёл equivalence gate");
  }
  return {
    packId: string(source.pack_id, "pack_id", SAFE_PACK_ID),
    sessionId: string(source.session_id, "session_id", SAFE_ID),
    profileId: string(source.profile_id, "profile_id", SAFE_ID),
    pointFrames: integer(source.point_frames, "point_frames"),
    poseFrames: integer(source.pose_frames, "pose_frames"),
    points: integer(source.points, "points"),
    meanPointsPerFrame: number(source.mean_points_per_frame, "mean_points_per_frame", true),
    p95FrameIntervalMs: number(source.p95_frame_interval_ms, "p95_frame_interval_ms", true),
    poseCoverageFraction: number(
      source.pose_coverage_fraction,
      "pose_coverage_fraction",
      true,
    ),
    equivalenceStatus: "passed",
    logicalContentSha256: string(
      source.logical_content_sha256,
      "logical_content_sha256",
      SHA256,
    ),
    createdAtUtc:
      source.created_at_utc === null || source.created_at_utc === undefined
        ? null
        : string(source.created_at_utc, "created_at_utc"),
  };
}

export function parseLidarReplayCatalog(value: unknown): LidarReplayCatalog {
  const source = record(value, "LiDAR catalog");
  if (source.schema_version !== "missioncore.lidar-replay-pack-catalog/v1") {
    throw new LidarReplayContractError("LiDAR catalog schema несовместима");
  }
  return {
    configured: boolean(source.configured, "configured"),
    validTotal: integer(source.valid_total, "valid_total"),
    invalidTotal: integer(source.invalid_total, "invalid_total"),
    duplicateTotal: integer(source.duplicate_total, "duplicate_total"),
    items: array(source.items, "items").map(packSummary),
  };
}

export function parseLidarReplayDetail(value: unknown): LidarReplayDetail {
  const source = record(value, "LiDAR detail");
  if (
    source.schema_version !== "missioncore.lidar-replay-pack-detail/v1"
    || source.access !== "read-only"
  ) {
    throw new LidarReplayContractError("LiDAR detail contract несовместим");
  }
  const quality = record(source.quality, "quality");
  const retention = record(quality.field_retention, "field_retention");
  const fieldRetention: Record<string, boolean> = {};
  for (const [key, retained] of Object.entries(retention)) {
    fieldRetention[key] = boolean(retained, `field_retention.${key}`);
  }
  const poseBinding = record(quality.pose_binding, "pose_binding");
  const equivalence = record(source.equivalence, "equivalence");
  if (equivalence.status !== "passed") {
    throw new LidarReplayContractError("LiDAR equivalence gate не пройден");
  }
  const readiness = record(source.readiness, "readiness");
  const stages = array(readiness.stages, "readiness.stages").map((value) => {
    const stage = record(value, "readiness stage");
    const readinessValue = stage.readiness;
    if (
      readinessValue !== "ready"
      && readinessValue !== "degraded"
      && readinessValue !== "blocked"
    ) {
      throw new LidarReplayContractError("Неизвестный LiDAR readiness status");
    }
    const normalizedReadiness: LidarStageReadiness["readiness"] = readinessValue;
    return {
      stage: string(stage.stage, "stage", SAFE_ID),
      readiness: normalizedReadiness,
      reasons: array(stage.reasons, "stage.reasons").map((reason) =>
        string(reason, "stage reason", SAFE_ID)
      ),
    };
  });
  return {
    pack: packSummary(source.pack),
    quality: {
      fieldRetention,
      pointCountPerFrame: distribution(quality.point_count_per_frame, "point_count"),
      pointFrameIntervalMs: distribution(
        quality.point_frame_interval_ms,
        "point_interval",
      ),
      intensity: distribution(quality.intensity_0_255, "intensity"),
      poseBinding: {
        thresholdMs: number(poseBinding.threshold_ms, "pose threshold") ?? 0,
        coveredPointFrames: integer(
          poseBinding.covered_point_frames,
          "covered point frames",
        ),
        coverageFraction: number(
          poseBinding.coverage_fraction,
          "pose coverage",
        ) ?? 0,
        nearestDeltaMs: distribution(
          poseBinding.nearest_delta_ms,
          "nearest pose delta",
        ),
      },
      limitations: array(quality.limitations, "limitations").map((item) =>
        string(item, "limitation")
      ),
    },
    equivalence: {
      status: "passed",
      arraysCompared: integer(equivalence.arrays_compared, "arrays_compared"),
      arrayMismatches: integer(
        equivalence.array_mismatches,
        "array_mismatches",
      ),
    },
    stages,
  };
}

function groundProvider(
  value: unknown,
  label: string,
): LidarGroundProviderSummary {
  const source = record(value, label);
  return {
    providerId: string(source.provider_id, `${label}.provider_id`, SAFE_ID),
    sourceCommit:
      source.source_commit === undefined || source.source_commit === null
        ? null
        : string(source.source_commit, `${label}.source_commit`, GIT_SHA1),
  };
}

function groundBranch(
  value: unknown,
  label: string,
): LidarGroundBenchmark["current"] {
  const source = record(value, label);
  return {
    provider: groundProvider(source.provider, `${label}.provider`),
    groundFraction: distribution(
      source.ground_fraction,
      `${label}.ground_fraction`,
    ),
    assignedFraction: distribution(
      source.assigned_fraction,
      `${label}.assigned_fraction`,
    ),
    latencyMs: distribution(source.latency_ms, `${label}.latency_ms`),
  };
}

function groundBenchmark(value: unknown): LidarGroundBenchmark {
  const source = record(value, "LiDAR ground benchmark");
  if (source.status !== "diagnostic-only") {
    throw new LidarReplayContractError("Ground benchmark status несовместим");
  }
  const inputDomain = record(source.input_domain, "input_domain");
  const normalization = inputDomain.normalization === undefined
    ? null
    : record(inputDomain.normalization, "input_domain.normalization");
  const labels = record(source.labels, "labels");
  const comparison = record(source.comparison, "comparison");
  const decision = record(source.decision, "decision");
  if (
    inputDomain.accepted !== false
    || labels.status !== "missing-independent-review"
    || labels.metrics_available !== false
    || comparison.is_accuracy_metric !== false
    || decision.status !== "do-not-promote-on-current-vendor-map"
    || decision.production_promotion !== false
  ) {
    throw new LidarReplayContractError(
      "Ground benchmark завышает readiness или accuracy",
    );
  }
  return {
    benchmarkId: string(
      source.benchmark_id,
      "benchmark_id",
      SAFE_GROUND_BENCHMARK_ID,
    ),
    replayPackId: string(source.replay_pack_id, "replay_pack_id", SAFE_PACK_ID),
    sessionId: string(source.session_id, "session_id", SAFE_ID),
    status: "diagnostic-only",
    frames: integer(source.frames, "frames"),
    points: integer(source.points, "points"),
    inputDomain: {
      accepted: false,
      representation: string(
        inputDomain.representation,
        "input_domain.representation",
        SAFE_ID,
      ),
      physicalSensorHeightKnown: boolean(
        inputDomain.physical_sensor_height_known,
        "input_domain.physical_sensor_height_known",
      ),
      sensorScanGeometryKnown: boolean(
        inputDomain.sensor_scan_geometry_known,
        "input_domain.sensor_scan_geometry_known",
      ),
      reason: string(inputDomain.reason, "input_domain.reason"),
      normalization: normalization
        ? {
            sensorHeightM:
              number(
                normalization.sensor_height_m,
                "normalization.sensor_height_m",
              ) ?? 0,
            mapVerticalOriginOffsetM:
              number(
                normalization.map_vertical_origin_offset_m,
                "normalization.map_vertical_origin_offset_m",
              ) ?? 0,
            heightEvidence: (() => {
              const value = normalization.height_evidence;
              if (
                value !== "missing"
                && value !== "operator-estimated"
                && value !== "runtime-calibrated"
              ) {
                throw new LidarReplayContractError(
                  "normalization.height_evidence: неизвестное значение",
                );
              }
              return value;
            })(),
          }
        : null,
    },
    labels: {
      status: "missing-independent-review",
      metricsAvailable: false,
    },
    current: groundBranch(source.current, "current"),
    candidate: groundBranch(source.candidate, "candidate"),
    comparison: {
      algorithmGroundIou: distribution(
        comparison.algorithm_to_algorithm_ground_iou,
        "comparison.algorithm_ground_iou",
      ),
      groundDisagreementFraction: distribution(
        comparison.ground_disagreement_fraction,
        "comparison.ground_disagreement_fraction",
      ),
      isAccuracyMetric: false,
    },
    decision: {
      status: "do-not-promote-on-current-vendor-map",
      productionPromotion: false,
      reasons: array(decision.reasons, "decision.reasons").map((reason) =>
        string(reason, "decision.reason")
      ),
      nextGate: string(decision.next_gate, "decision.next_gate"),
    },
    createdAtUtc:
      source.created_at_utc === null || source.created_at_utc === undefined
        ? null
        : string(source.created_at_utc, "created_at_utc"),
  };
}

export function parseLidarGroundBenchmarkCatalog(
  value: unknown,
): LidarGroundBenchmarkCatalog {
  const source = record(value, "LiDAR ground catalog");
  if (
    source.schema_version
      !== "missioncore.lidar-ground-benchmark-catalog/v1"
    || source.access !== "read-only"
  ) {
    throw new LidarReplayContractError("LiDAR ground catalog несовместим");
  }
  return {
    configured: boolean(source.configured, "configured"),
    validTotal: integer(source.valid_total, "valid_total"),
    invalidTotal: integer(source.invalid_total, "invalid_total"),
    items: array(source.items, "items").map(groundBenchmark),
  };
}

export function parseLidarGroundFrame(value: unknown): LidarGroundFrame {
  const source = record(value, "LiDAR ground frame");
  if (
    source.schema_version !== "missioncore.lidar-ground-frame/v1"
    || source.access !== "read-only"
    || source.ground_truth !== false
    || source.coordinate_frame !== "map"
    || source.distance_unit !== "m"
  ) {
    throw new LidarReplayContractError("LiDAR ground frame contract несовместим");
  }
  const pointCount = integer(source.point_count, "point_count");
  if (pointCount < 1 || pointCount > 200_000) {
    throw new LidarReplayContractError("LiDAR ground frame слишком большой");
  }
  const points = array(source.points_xyz_m, "points_xyz_m");
  if (points.length !== pointCount) {
    throw new LidarReplayContractError("Количество LiDAR points не совпадает");
  }
  const pointsXyzM = points.map((value, index): [number, number, number] => {
    const tuple = array(value, `points_xyz_m[${index}]`);
    if (tuple.length !== 3) {
      throw new LidarReplayContractError("LiDAR point должен содержать XYZ");
    }
    return [
      number(tuple[0], `points_xyz_m[${index}].x`) ?? 0,
      number(tuple[1], `points_xyz_m[${index}].y`) ?? 0,
      number(tuple[2], `points_xyz_m[${index}].z`) ?? 0,
    ];
  });
  const intensity = array(source.intensity_0_255, "intensity_0_255");
  if (intensity.length !== pointCount) {
    throw new LidarReplayContractError("Количество intensity не совпадает");
  }
  const intensity0To255 = intensity.map((value, index) => {
    const parsed = integer(value, `intensity_0_255[${index}]`);
    if (parsed > 255) {
      throw new LidarReplayContractError("LiDAR intensity вне диапазона");
    }
    return parsed;
  });
  const masks = record(source.masks, "masks");
  const counts = record(source.counts, "counts");
  const currentGround = groundMask(
    masks.current_ground,
    "masks.current_ground",
    pointCount,
  );
  const candidateGround = groundMask(
    masks.candidate_ground,
    "masks.candidate_ground",
    pointCount,
  );
  const disagreement = groundMask(
    masks.disagreement,
    "masks.disagreement",
    pointCount,
  );
  const parsedCounts = {
    currentGround: integer(counts.current_ground, "counts.current_ground"),
    candidateGround: integer(
      counts.candidate_ground,
      "counts.candidate_ground",
    ),
    disagreement: integer(counts.disagreement, "counts.disagreement"),
  };
  const frameIndex = integer(source.frame_index, "frame_index");
  const frameCount = integer(source.frame_count, "frame_count");
  if (
    frameCount < 1
    || frameIndex >= frameCount
    || parsedCounts.currentGround !== currentGround.reduce((sum, item) => sum + item, 0)
    || parsedCounts.candidateGround !== candidateGround.reduce((sum, item) => sum + item, 0)
    || parsedCounts.disagreement !== disagreement.reduce((sum, item) => sum + item, 0)
    || disagreement.some(
      (item, index) => item !== Number(currentGround[index] !== candidateGround[index]),
    )
  ) {
    throw new LidarReplayContractError("LiDAR ground frame несовместим");
  }
  return {
    benchmarkId: string(
      source.benchmark_id,
      "benchmark_id",
      SAFE_GROUND_BENCHMARK_ID,
    ),
    replayPackId: string(source.replay_pack_id, "replay_pack_id", SAFE_PACK_ID),
    sessionId: string(source.session_id, "session_id", SAFE_ID),
    frameIndex,
    frameCount,
    captureSequence: integer(source.capture_sequence, "capture_sequence"),
    pointCount,
    coordinateFrame: "map",
    distanceUnit: "m",
    pointsXyzM,
    intensity0To255,
    masks: {
      currentGround,
      currentAssigned: groundMask(
        masks.current_assigned,
        "masks.current_assigned",
        pointCount,
      ),
      candidateGround,
      candidateAssigned: groundMask(
        masks.candidate_assigned,
        "masks.candidate_assigned",
        pointCount,
      ),
      disagreement,
    },
    counts: parsedCounts,
    groundTruth: false,
  };
}

function fieldReviewWindowSummary(
  value: unknown,
  expectedIndex: number,
): LidarFieldReviewWindowSummary {
  const source = record(value, `field-review window ${expectedIndex}`);
  const index = integer(source.index, "window.index");
  const startSeconds = number(source.start_seconds, "window.start_seconds") ?? 0;
  const endSeconds = number(source.end_seconds, "window.end_seconds") ?? 0;
  if (index !== expectedIndex || startSeconds >= endSeconds) {
    throw new LidarReplayContractError("LiDAR field-review window несовместим");
  }
  return {
    index,
    key: string(source.key, "window.key", SAFE_FIELD_KEY),
    label: string(source.label, "window.label"),
    startSeconds,
    endSeconds,
    midpointSeconds:
      number(source.midpoint_seconds, "window.midpoint_seconds") ?? 0,
    sourceLidarSamples: integer(
      source.source_lidar_samples,
      "window.source_lidar_samples",
    ),
    sourcePointCount: integer(
      source.source_point_count,
      "window.source_point_count",
    ),
    displayPointCount: integer(
      source.display_point_count,
      "window.display_point_count",
    ),
    sourceFrameStart: integer(
      source.source_frame_start,
      "window.source_frame_start",
    ),
    sourceFrameEnd: integer(
      source.source_frame_end,
      "window.source_frame_end",
    ),
    previewSourceFrameIndex: integer(
      source.preview_source_frame_index,
      "window.preview_source_frame_index",
    ),
    previewSessionSeconds:
      number(
        source.preview_session_seconds,
        "window.preview_session_seconds",
      ) ?? 0,
  };
}

function fieldReviewBranch(
  value: unknown,
  label: string,
): LidarFieldReview["metrics"]["current"] {
  const source = record(value, label);
  return {
    provider: groundProvider(source.provider, `${label}.provider`),
    groundFraction: distribution(
      source.ground_fraction,
      `${label}.ground_fraction`,
    ),
    latencyMs: distribution(source.latency_ms, `${label}.latency_ms`),
  };
}

function fieldReview(value: unknown): LidarFieldReview {
  const source = record(value, "LiDAR field review");
  const sourceEvidence = record(source.source, "field-review source");
  const selection = record(source.selection, "field-review selection");
  const sampling = record(selection.sampling, "field-review sampling");
  const metrics = record(source.metrics, "field-review metrics");
  const comparison = record(metrics.comparison, "field-review comparison");
  const decision = record(source.decision, "field-review decision");
  const authority = record(source.authority, "field-review authority");
  if (
    source.status !== "diagnostic-only"
    || source.ground_truth !== false
    || sourceEvidence.representation !== "legacy-e10-vendor-map-with-pose"
    || sourceEvidence.intensity_available !== false
    || sourceEvidence.raw_scan_accepted !== false
    || selection.purpose !== "operator-readable-central-urban-field-review"
    || selection.accumulation !== "per-source-frame masks accumulated in map frame"
    || sampling.method !== "uniform-point-index-per-window"
    || comparison.is_accuracy_metric !== false
    || decision.status !== "visual-review-only"
    || decision.production_promotion !== false
    || authority.commands_enabled !== false
    || authority.navigation_or_safety_accepted !== false
  ) {
    throw new LidarReplayContractError(
      "LiDAR field review завышает readiness или меняет evidence",
    );
  }
  const windows = array(source.windows, "field-review windows").map(
    fieldReviewWindowSummary,
  );
  const defaultWindowIndex = integer(
    selection.default_window_index,
    "selection.default_window_index",
  );
  const maximumPointsPerWindow = integer(
    sampling.maximum_points_per_window,
    "sampling.maximum_points_per_window",
  );
  if (
    windows.length < 1
    || defaultWindowIndex >= windows.length
    || maximumPointsPerWindow < 1
    || maximumPointsPerWindow > 80_000
    || windows.some(
      (window) =>
        window.sourceLidarSamples < 1
        || window.sourcePointCount < window.displayPointCount
        || window.displayPointCount < 1
        || window.displayPointCount > maximumPointsPerWindow,
    )
  ) {
    throw new LidarReplayContractError("LiDAR field-review selection несовместим");
  }
  return {
    reviewId: string(source.review_id, "review_id", SAFE_FIELD_REVIEW_ID),
    displayName: string(source.display_name, "display_name"),
    sessionId: string(source.session_id, "session_id", SAFE_ID),
    sourcePackId: string(
      source.source_pack_id,
      "source_pack_id",
      SAFE_E10_PACK_ID,
    ),
    status: "diagnostic-only",
    source: {
      timelineStartSeconds:
        number(
          sourceEvidence.timeline_start_seconds,
          "source.timeline_start_seconds",
        ) ?? 0,
      timelineEndSeconds:
        number(
          sourceEvidence.timeline_end_seconds,
          "source.timeline_end_seconds",
        ) ?? 0,
      availableLidarFrames: integer(
        sourceEvidence.available_lidar_frames,
        "source.available_lidar_frames",
      ),
      pointCount: integer(sourceEvidence.point_count, "source.point_count"),
      representation: "legacy-e10-vendor-map-with-pose",
      intensityAvailable: false,
      rawScanAccepted: false,
    },
    selection: {
      purpose: "operator-readable-central-urban-field-review",
      defaultWindowIndex,
      accumulation: "per-source-frame masks accumulated in map frame",
      maximumPointsPerWindow,
    },
    windows,
    metrics: {
      sourceSamples: integer(metrics.source_samples, "metrics.source_samples"),
      current: fieldReviewBranch(metrics.current, "metrics.current"),
      candidate: fieldReviewBranch(metrics.candidate, "metrics.candidate"),
      comparison: {
        algorithmGroundIou: distribution(
          comparison.algorithm_to_algorithm_ground_iou,
          "metrics.comparison.algorithm_ground_iou",
        ),
        groundDisagreementFraction: distribution(
          comparison.ground_disagreement_fraction,
          "metrics.comparison.ground_disagreement_fraction",
        ),
        isAccuracyMetric: false,
      },
    },
    decision: {
      status: "visual-review-only",
      productionPromotion: false,
      reasons: array(decision.reasons, "decision.reasons").map((reason) =>
        string(reason, "decision.reason")
      ),
    },
    createdAtUtc:
      source.created_at_utc === null || source.created_at_utc === undefined
        ? null
        : string(source.created_at_utc, "created_at_utc"),
    groundTruth: false,
    authority: {
      commandsEnabled: false,
      navigationOrSafetyAccepted: false,
    },
  };
}

export function parseLidarFieldReviewCatalog(
  value: unknown,
): LidarFieldReviewCatalog {
  const source = record(value, "LiDAR field-review catalog");
  if (
    source.schema_version !== "missioncore.lidar-field-review-catalog/v1"
    || source.access !== "read-only"
  ) {
    throw new LidarReplayContractError("LiDAR field-review catalog несовместим");
  }
  return {
    configured: boolean(source.configured, "configured"),
    validTotal: integer(source.valid_total, "valid_total"),
    invalidTotal: integer(source.invalid_total, "invalid_total"),
    items: array(source.items, "items").map(fieldReview),
  };
}

export function parseLidarFieldReviewWindow(
  value: unknown,
): LidarFieldReviewWindow {
  const source = record(value, "LiDAR field-review window");
  const reviewId = string(
    source.review_id,
    "review_id",
    SAFE_FIELD_REVIEW_ID,
  );
  if (
    source.schema_version !== "missioncore.lidar-field-review-window/v1"
    || source.access !== "read-only"
    || source.ground_truth !== false
    || source.coordinate_frame !== "map"
    || source.distance_unit !== "m"
  ) {
    throw new LidarReplayContractError("LiDAR field-review window несовместим");
  }
  const authority = record(source.authority, "authority");
  const intensity = record(source.intensity, "intensity");
  if (
    authority.commands_enabled !== false
    || authority.navigation_or_safety_accepted !== false
    || intensity.available !== false
  ) {
    throw new LidarReplayContractError("LiDAR field-review authority несовместим");
  }
  const pointCount = integer(source.point_count, "point_count");
  if (pointCount < 1 || pointCount > 80_000) {
    throw new LidarReplayContractError("LiDAR field-review window слишком большой");
  }
  const points = array(source.points_xyz_m, "points_xyz_m");
  if (points.length !== pointCount) {
    throw new LidarReplayContractError("Количество field-review points не совпадает");
  }
  const pointsXyzM = points.map((value, index): [number, number, number] => {
    const tuple = array(value, `points_xyz_m[${index}]`);
    if (tuple.length !== 3) {
      throw new LidarReplayContractError("LiDAR point должен содержать XYZ");
    }
    return [
      number(tuple[0], `points_xyz_m[${index}].x`) ?? 0,
      number(tuple[1], `points_xyz_m[${index}].y`) ?? 0,
      number(tuple[2], `points_xyz_m[${index}].z`) ?? 0,
    ];
  });
  const masks = record(source.masks, "masks");
  const currentGround = groundMask(
    masks.current_ground,
    "masks.current_ground",
    pointCount,
  );
  const currentAssigned = groundMask(
    masks.current_assigned,
    "masks.current_assigned",
    pointCount,
  );
  const candidateGround = groundMask(
    masks.candidate_ground,
    "masks.candidate_ground",
    pointCount,
  );
  const candidateAssigned = groundMask(
    masks.candidate_assigned,
    "masks.candidate_assigned",
    pointCount,
  );
  const disagreement = groundMask(
    masks.disagreement,
    "masks.disagreement",
    pointCount,
  );
  const counts = record(source.counts, "counts");
  const parsedCounts = {
    currentGround: integer(counts.current_ground, "counts.current_ground"),
    candidateGround: integer(
      counts.candidate_ground,
      "counts.candidate_ground",
    ),
    disagreement: integer(counts.disagreement, "counts.disagreement"),
  };
  const windowIndex = integer(source.window_index, "window_index");
  const windowCount = integer(source.window_count, "window_count");
  const window = fieldReviewWindowSummary(source.window, windowIndex);
  const expectedPreviewUrl =
    `/api/v1/lidar/field-reviews/${reviewId}/windows/${windowIndex}/preview`;
  if (
    windowCount < 1
    || windowIndex >= windowCount
    || window.displayPointCount !== pointCount
    || parsedCounts.currentGround
      !== currentGround.reduce((sum, item) => sum + item, 0)
    || parsedCounts.candidateGround
      !== candidateGround.reduce((sum, item) => sum + item, 0)
    || parsedCounts.disagreement
      !== disagreement.reduce((sum, item) => sum + item, 0)
    || disagreement.some(
      (item, index) =>
        item !== Number(currentGround[index] !== candidateGround[index]),
    )
    || source.preview_url !== expectedPreviewUrl
  ) {
    throw new LidarReplayContractError("LiDAR field-review content несовместим");
  }
  return {
    reviewId,
    displayName: string(source.display_name, "display_name"),
    sessionId: string(source.session_id, "session_id", SAFE_ID),
    sourcePackId: string(
      source.source_pack_id,
      "source_pack_id",
      SAFE_E10_PACK_ID,
    ),
    windowIndex,
    windowCount,
    window,
    pointCount,
    coordinateFrame: "map",
    distanceUnit: "m",
    pointsXyzM,
    intensity0To255: null,
    intensity: {
      available: false,
      reason: string(intensity.reason, "intensity.reason"),
    },
    masks: {
      currentGround,
      currentAssigned,
      candidateGround,
      candidateAssigned,
      disagreement,
    },
    counts: parsedCounts,
    previewUrl: expectedPreviewUrl,
    groundTruth: false,
    authority: {
      commandsEnabled: false,
      navigationOrSafetyAccepted: false,
    },
  };
}

async function responseJson(
  response: Response,
  fallback: string,
): Promise<unknown> {
  let value: unknown;
  try {
    value = await response.json();
  } catch {
    throw new LidarReplayApiError(fallback, response.status);
  }
  if (!response.ok) {
    const detail = record(value, "API error").detail;
    throw new LidarReplayApiError(
      typeof detail === "string" && detail.trim() ? detail : fallback,
      response.status,
    );
  }
  return value;
}

export async function fetchLidarReplayCatalog(
  options: { signal?: AbortSignal; fetcher?: LidarFetch } = {},
): Promise<LidarReplayCatalog> {
  const fetcher = options.fetcher ?? fetch;
  const response = await fetcher("/api/v1/lidar/replay-packs?limit=50", {
    method: "GET",
    headers: { Accept: "application/json" },
    signal: options.signal,
  });
  return parseLidarReplayCatalog(
    await responseJson(response, "Не удалось получить каталог LiDAR replay."),
  );
}

export async function fetchLidarReplayDetail(
  packId: string,
  options: { signal?: AbortSignal; fetcher?: LidarFetch } = {},
): Promise<LidarReplayDetail> {
  if (!SAFE_PACK_ID.test(packId)) {
    throw new LidarReplayContractError("Некорректный LiDAR pack id");
  }
  const fetcher = options.fetcher ?? fetch;
  const response = await fetcher(`/api/v1/lidar/replay-packs/${packId}`, {
    method: "GET",
    headers: { Accept: "application/json" },
    signal: options.signal,
  });
  return parseLidarReplayDetail(
    await responseJson(response, "Не удалось получить LiDAR quality report."),
  );
}

export async function fetchLidarGroundBenchmarks(
  packId: string,
  options: { signal?: AbortSignal; fetcher?: LidarFetch } = {},
): Promise<LidarGroundBenchmarkCatalog> {
  if (!SAFE_PACK_ID.test(packId)) {
    throw new LidarReplayContractError("Некорректный LiDAR pack id");
  }
  const fetcher = options.fetcher ?? fetch;
  const response = await fetcher(
    `/api/v1/lidar/ground-benchmarks?pack_id=${encodeURIComponent(packId)}&limit=20`,
    {
      method: "GET",
      headers: { Accept: "application/json" },
      signal: options.signal,
    },
  );
  return parseLidarGroundBenchmarkCatalog(
    await responseJson(response, "Не удалось получить LiDAR ground benchmark."),
  );
}

export async function fetchLidarGroundFrame(
  benchmarkId: string,
  frameIndex: number,
  options: { signal?: AbortSignal; fetcher?: LidarFetch } = {},
): Promise<LidarGroundFrame> {
  if (
    !SAFE_GROUND_BENCHMARK_ID.test(benchmarkId)
    || !Number.isInteger(frameIndex)
    || frameIndex < 0
  ) {
    throw new LidarReplayContractError("Некорректный LiDAR ground frame");
  }
  const fetcher = options.fetcher ?? fetch;
  const response = await fetcher(
    `/api/v1/lidar/ground-benchmarks/${benchmarkId}/frames/${frameIndex}`,
    {
      method: "GET",
      headers: { Accept: "application/json" },
      signal: options.signal,
    },
  );
  return parseLidarGroundFrame(
    await responseJson(response, "Не удалось получить LiDAR ground frame."),
  );
}

export async function fetchLidarFieldReviews(
  options: { signal?: AbortSignal; fetcher?: LidarFetch } = {},
): Promise<LidarFieldReviewCatalog> {
  const fetcher = options.fetcher ?? fetch;
  const response = await fetcher("/api/v1/lidar/field-reviews?limit=10", {
    method: "GET",
    headers: { Accept: "application/json" },
    signal: options.signal,
  });
  return parseLidarFieldReviewCatalog(
    await responseJson(response, "Не удалось получить полевой LiDAR review."),
  );
}

export async function fetchLidarFieldReviewWindow(
  reviewId: string,
  windowIndex: number,
  options: { signal?: AbortSignal; fetcher?: LidarFetch } = {},
): Promise<LidarFieldReviewWindow> {
  if (
    !SAFE_FIELD_REVIEW_ID.test(reviewId)
    || !Number.isInteger(windowIndex)
    || windowIndex < 0
  ) {
    throw new LidarReplayContractError(
      "Некорректное окно полевого LiDAR review",
    );
  }
  const fetcher = options.fetcher ?? fetch;
  const response = await fetcher(
    `/api/v1/lidar/field-reviews/${reviewId}/windows/${windowIndex}`,
    {
      method: "GET",
      headers: { Accept: "application/json" },
      signal: options.signal,
    },
  );
  return parseLidarFieldReviewWindow(
    await responseJson(
      response,
      "Не удалось получить окно полевого LiDAR review.",
    ),
  );
}
