import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";

import {
  ZONE_SOURCE_GENERATION_SCHEMA_VERSION,
  normalizeZoneSourceGeneration,
  validateDataProductPublish,
} from "../src/index.mjs";
import { loadZoneSourceProfile } from "../../../services/map-gateway/src/zone-source-snapshot.mjs";

const generatedAt = "2025-06-03T11:05:00.000Z";
const snapshotDigest = "a".repeat(64);
const snapshot = normalizeZoneSourceGeneration({
  schemaVersion: ZONE_SOURCE_GENERATION_SCHEMA_VERSION,
  profileId: "moscow-pmd-slow-zones",
  authorityId: "moscow-department-of-transport",
  datasetId: "pmd-slow-zones",
  adapterId: "depttrans-mmap-snapshot-v1",
  sourceRevision: "pmd-slow-zones-202506031405",
  contentDigest: snapshotDigest,
  generatedAt,
  timezone: "Europe/Moscow",
  complete: true,
  zones: [{
    nativeId: "1478",
    displayName: "Петровский парк_6 (15 км/ч)",
    geometry: {
      type: "Polygon",
      coordinates: [[
        [37.60, 55.74],
        [37.62, 55.74],
        [37.62, 55.76],
        [37.60, 55.74],
      ]],
    },
    areaSquareMeters: 75689,
    appliesToKicksharing: false,
    appliesToCouriers: true,
    maxSpeedKph: 15,
    weeklySpeedSchedule: [{
      dayOfWeek: 1,
      startTime: "00:00:00",
      endTime: "23:59:00",
      speedLimitKph: 15,
    }],
  }],
});

assert.equal(snapshot.complete, true);
assert.equal(snapshot.sourceKind, "versioned_snapshot");
assert.equal(snapshot.facts.length, 1);
assert.equal(snapshot.facts[0].sourceId, "depttrans-pmd-slow-zone-1478");
assert.equal(snapshot.facts[0].observedAt, generatedAt);
assert.equal(snapshot.facts[0].geometry.type, "Polygon");
assert.equal(snapshot.facts[0].attributes.dataset_authority, "moscow-department-of-transport");
assert.equal(snapshot.facts[0].attributes.dataset_id, "pmd-slow-zones");
assert.equal(snapshot.facts[0].attributes.source_adapter, "depttrans-mmap-snapshot-v1");
assert.deepEqual(snapshot.facts[0].attributes.weekly_speed_schedule, ["1@00:00:00-23:59:00=15"]);
assert.match(snapshot.sourceRevision, new RegExp(`@sha256:${snapshotDigest}$`));
assert.equal(validateDataProductPublish({
  schemaVersion: "nodedc.data-product.publish/v1",
  batch: {
    runId: "zones-snapshot-1",
    sequence: 0,
    idempotencyKey: "zones-snapshot-1.batch-0",
    mode: "replace",
    generationAt: generatedAt,
  },
  facts: snapshot.facts,
}).ok, true);

const apiSnapshot = normalizeZoneSourceGeneration({
  schemaVersion: ZONE_SOURCE_GENERATION_SCHEMA_VERSION,
  authorityId: "moscow-department-of-transport",
  datasetId: "pmd-slow-zones",
  adapterId: "depttrans-api-snapshot-v1",
  sourceRevision: "pmd-slow-zones-20260721",
  contentDigest: "b".repeat(64),
  generatedAt: "2026-07-21T09:00:00.000Z",
  timezone: "Europe/Moscow",
  complete: true,
  zones: [{
    nativeId: "1478",
    displayName: "Петровский парк_6 (15 км/ч)",
    geometry: snapshot.facts[0].geometry,
  }],
});
assert.equal(apiSnapshot.facts[0].sourceId, snapshot.facts[0].sourceId);
assert.equal(apiSnapshot.facts[0].attributes.source_adapter, "depttrans-api-snapshot-v1");

const gelios = normalizeZoneSourceGeneration({
  schemaVersion: ZONE_SOURCE_GENERATION_SCHEMA_VERSION,
  authorityId: "gelios-account",
  datasetId: "gelios-geofences",
  adapterId: "gelios-rest-v1",
  sourceRevision: "gelios-rest-v1",
  generatedAt: "2026-07-21T09:00:00.000Z",
  complete: true,
  zones: [{
    id: 1478,
    name: "Account geofence",
    type: "polygon",
    points: [
      { latitude: 55.74, longitude: 37.60 },
      { latitude: 55.74, longitude: 37.62 },
      { latitude: 55.76, longitude: 37.62 },
    ],
  }],
});
assert.equal(gelios.facts[0].sourceId, "gelios-zone-1478");
assert.notEqual(gelios.facts[0].sourceId, snapshot.facts[0].sourceId);

assert.throws(() => normalizeZoneSourceGeneration({
  schemaVersion: ZONE_SOURCE_GENERATION_SCHEMA_VERSION,
  authorityId: "gelios-account",
  datasetId: "pmd-slow-zones",
  adapterId: "depttrans-mmap-snapshot-v1",
  contentDigest: snapshotDigest,
  generatedAt,
  complete: true,
  zones: [],
}), /zone_source_authority_mismatch/);
assert.throws(() => normalizeZoneSourceGeneration({
  schemaVersion: ZONE_SOURCE_GENERATION_SCHEMA_VERSION,
  authorityId: "moscow-department-of-transport",
  datasetId: "pmd-slow-zones",
  adapterId: "depttrans-mmap-snapshot-v1",
  contentDigest: snapshotDigest,
  generatedAt,
  complete: true,
  zones: [{ snapshotKey: "unknown", displayName: "Unknown", geometry: snapshot.facts[0].geometry }],
}), /zone_source_identity_crosswalk_required/);
assert.throws(() => normalizeZoneSourceGeneration({
  schemaVersion: ZONE_SOURCE_GENERATION_SCHEMA_VERSION,
  authorityId: "moscow-department-of-transport",
  datasetId: "pmd-slow-zones",
  adapterId: "depttrans-mmap-snapshot-v1",
  contentDigest: snapshotDigest,
  generatedAt,
  complete: false,
  zones: [],
}), /zone_source_generation_incomplete/);

const actualSource = await loadZoneSourceProfile(
  fileURLToPath(new URL("../../../services/map-gateway/zone-sources", import.meta.url)),
  "moscow-pmd-slow-zones",
);
const actual = normalizeZoneSourceGeneration(actualSource.generation);
assert.equal(actual.facts.length, 903);
assert.equal(actual.facts[0].sourceId.startsWith("depttrans-pmd-slow-zone-"), true);
assert.equal(actual.facts.every((fact) => fact.attributes.dataset_authority === "moscow-department-of-transport"), true);
assert.equal(actual.facts.every((fact) => fact.attributes.dataset_id === "pmd-slow-zones"), true);
assert.equal(actual.facts.every((fact) => fact.attributes.source_adapter === "depttrans-mmap-snapshot-v1"), true);
assert.equal(actual.facts.every((fact) => fact.attributes.weekly_speed_schedule.length === 7), true);
assert.equal(actual.facts.every((fact) => Number(fact.attributes.area_square_meters) > 0), true);

console.log("external-provider zone source: ok");
