/* eslint-disable @typescript-eslint/no-explicit-any */
/**
 * POST /api/eterra/export-bundle (v2 — sync-first)
 *
 * Flow:
 *   1. Sync TERENURI_ACTIVE + CLADIRI_ACTIVE to local DB (skip if fresh)
 *   2. Enrich parcels with CF/owner/address data (magic mode only, skip if enriched)
 *   3. Build GPKG + CSV from local DB
 *   4. Return ZIP
 *
 * Body: { siruta, jobId?, mode?: "base"|"magic", forceSync?: boolean }
 */
import JSZip from "jszip";
import { prisma } from "@/core/storage/prisma";
import { EterraClient } from "@/modules/parcel-sync/services/eterra-client";
import { getEpsg3844Wkt } from "@/modules/parcel-sync/services/reproject";
import { buildGpkg } from "@/modules/parcel-sync/services/gpkg-export";
import { syncLayer } from "@/modules/parcel-sync/services/sync-service";
import {
  enrichFeatures,
  getLayerFreshness,
  isFresh,
  type FeatureEnrichment,
} from "@/modules/parcel-sync/services/enrich-service";
import {
  clearProgress,
  setProgress,
} from "@/modules/parcel-sync/services/progress-store";
import {
  getSessionCredentials,
  registerJob,
  unregisterJob,
} from "@/modules/parcel-sync/services/session-store";
import { syncNoGeometryParcels } from "@/modules/parcel-sync/services/no-geom-sync";
import type { GeoJsonFeature } from "@/modules/parcel-sync/services/esri-geojson";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

type ExportBundleRequest = {
  username?: string;
  password?: string;
  siruta?: string | number;
  jobId?: string;
  mode?: "base" | "magic";
  forceSync?: boolean;
  includeNoGeometry?: boolean;
};

const validate = (body: ExportBundleRequest) => {
  const session = getSessionCredentials();
  const username = String(
    body.username || session?.username || process.env.ETERRA_USERNAME || "",
  ).trim();
  const password = String(
    body.password || session?.password || process.env.ETERRA_PASSWORD || "",
  ).trim();
  const siruta = String(body.siruta ?? "").trim();
  const jobId = body.jobId ? String(body.jobId).trim() : undefined;
  const mode = body.mode === "magic" ? "magic" : "base";
  const forceSync = body.forceSync === true;
  const includeNoGeometry = body.includeNoGeometry === true;

  if (!username) throw new Error("Email is required");
  if (!password) throw new Error("Password is required");
  if (!/^\d+$/.test(siruta)) throw new Error("SIRUTA must be numeric");

  return {
    username,
    password,
    siruta,
    jobId,
    mode,
    forceSync,
    includeNoGeometry,
  };
};

const scheduleClear = (jobId?: string) => {
  if (!jobId) return;
  setTimeout(() => clearProgress(jobId), 60_000);
};

const csvEscape = (val: unknown) => {
  const s = String(val ?? "").replace(/"/g, '""');
  return `"${s}"`;
};

export async function POST(req: Request) {
  let jobId: string | undefined;
  let message: string | undefined;
  let phase = "Inițializare";
  let note: string | undefined;
  let status: "running" | "done" | "error" = "running";
  let downloaded = 0;
  let total: number | undefined;
  let completedWeight = 0;
  let currentWeight = 0;
  let phaseTotal: number | undefined;
  let phaseCurrent: number | undefined;

  const pushProgress = () => {
    if (!jobId) return;
    setProgress({
      jobId,
      downloaded,
      total,
      status,
      phase,
      note,
      message,
      phaseCurrent,
      phaseTotal,
    });
  };

  const updateOverall = (fraction = 0) => {
    const overall = completedWeight + currentWeight * fraction;
    downloaded = Number(Math.min(100, Math.max(0, overall)).toFixed(1));
    total = 100;
    pushProgress();
  };

  const setPhaseState = (next: string, weight: number, nextTotal?: number) => {
    phase = next;
    currentWeight = weight;
    phaseTotal = nextTotal;
    phaseCurrent = nextTotal ? 0 : undefined;
    note = undefined;
    updateOverall(0);
  };

  const updatePhaseProgress = (value: number, nextTotal?: number) => {
    if (typeof nextTotal === "number") phaseTotal = nextTotal;
    if (phaseTotal && phaseTotal > 0) {
      phaseCurrent = value;
      updateOverall(Math.min(1, value / phaseTotal));
    } else {
      phaseCurrent = undefined;
      updateOverall(0);
    }
  };

  const finishPhase = () => {
    completedWeight += currentWeight;
    currentWeight = 0;
    phaseTotal = undefined;
    phaseCurrent = undefined;
    note = undefined;
    updateOverall(0);
  };

  const withHeartbeat = async <T>(task: () => Promise<T>) => {
    let tick = 0.1;
    updatePhaseProgress(tick, 1);
    const interval = setInterval(() => {
      tick = Math.min(0.9, tick + 0.05);
      updatePhaseProgress(tick, 1);
    }, 1200);
    try {
      return await task();
    } finally {
      clearInterval(interval);
    }
  };

  try {
    const body = (await req.json()) as ExportBundleRequest;
    const validated = validate(body);
    jobId = validated.jobId;
    if (jobId) registerJob(jobId);
    pushProgress();

    const hasNoGeom = validated.includeNoGeometry;
    const weights =
      validated.mode === "magic"
        ? hasNoGeom
          ? { sync: 35, noGeom: 10, enrich: 30, gpkg: 15, zip: 10 }
          : { sync: 40, noGeom: 0, enrich: 35, gpkg: 15, zip: 10 }
        : hasNoGeom
          ? { sync: 45, noGeom: 15, enrich: 0, gpkg: 25, zip: 15 }
          : { sync: 55, noGeom: 0, enrich: 0, gpkg: 30, zip: 15 };

    /* ══════════════════════════════════════════════════════════ */
    /*  Phase 1: Sync layers to local DB                         */
    /* ══════════════════════════════════════════════════════════ */
    setPhaseState("Verificare date locale", weights.sync, 2);

    const terenuriLayerId = "TERENURI_ACTIVE";
    const cladiriLayerId = "CLADIRI_ACTIVE";

    const [terenuriStatus, cladiriStatus] = await Promise.all([
      getLayerFreshness(validated.siruta, terenuriLayerId),
      getLayerFreshness(validated.siruta, cladiriLayerId),
    ]);

    const terenuriNeedsSync =
      validated.forceSync ||
      !isFresh(terenuriStatus.lastSynced) ||
      terenuriStatus.featureCount === 0;
    const cladiriNeedsSync =
      validated.forceSync ||
      !isFresh(cladiriStatus.lastSynced) ||
      cladiriStatus.featureCount === 0;

    if (terenuriNeedsSync || cladiriNeedsSync) {
      if (terenuriNeedsSync) {
        phase = "Sincronizare terenuri";
        note =
          terenuriStatus.featureCount > 0
            ? "Re-sync (date expirate)"
            : "Sync inițial";
        pushProgress();

        const syncResult = await syncLayer(
          validated.username,
          validated.password,
          validated.siruta,
          terenuriLayerId,
          { forceFullSync: validated.forceSync, jobId, isSubStep: true },
        );
        if (syncResult.status === "error") {
          throw new Error(syncResult.error ?? "Sync terenuri failed");
        }
      }
      updatePhaseProgress(1, 2);

      if (cladiriNeedsSync) {
        phase = "Sincronizare clădiri";
        note =
          cladiriStatus.featureCount > 0
            ? "Re-sync (date expirate)"
            : "Sync inițial";
        pushProgress();

        const syncResult = await syncLayer(
          validated.username,
          validated.password,
          validated.siruta,
          cladiriLayerId,
          { forceFullSync: validated.forceSync, jobId, isSubStep: true },
        );
        if (syncResult.status === "error") {
          throw new Error(syncResult.error ?? "Sync clădiri failed");
        }
      }
      updatePhaseProgress(2, 2);
    } else {
      note = "Date proaspete în baza de date — skip sync";
      pushProgress();
      updatePhaseProgress(2, 2);
    }
    // Sync admin layers (lightweight, non-fatal)
    for (const adminLayer of ["LIMITE_INTRAV_DYNAMIC", "LIMITE_UAT"]) {
      try {
        await syncLayer(
          validated.username,
          validated.password,
          validated.siruta,
          adminLayer,
          { jobId, isSubStep: true },
        );
      } catch {
        // admin layers are best-effort
      }
    }
    finishPhase();

    /* ══════════════════════════════════════════════════════════ */
    /*  Phase 1b: Import no-geometry parcels (optional)          */
    /* ══════════════════════════════════════════════════════════ */
    let noGeomImported = 0;
    let noGeomCleaned = 0;
    let noGeomSkipped = 0;
    if (hasNoGeom && weights.noGeom > 0) {
      setPhaseState("Import parcele fără geometrie", weights.noGeom, 1);
      const noGeomClient = await EterraClient.create(
        validated.username,
        validated.password,
        { timeoutMs: 120_000 },
      );

      const noGeomResult = await syncNoGeometryParcels(
        noGeomClient,
        validated.siruta,
        {
          onProgress: (done, tot, ph) => {
            phase = ph;
            updatePhaseProgress(done, tot);
          },
          // workspacePk will be auto-resolved from DB/ArcGIS inside the service
        },
      );

      if (noGeomResult.status === "error") {
        // Non-fatal: log but continue with export
        note = `Avertisment: ${noGeomResult.error}`;
        pushProgress();
      } else {
        noGeomImported = noGeomResult.imported;
        noGeomCleaned = noGeomResult.cleaned;
        noGeomSkipped = noGeomResult.skipped;
        const cleanedNote =
          noGeomResult.cleaned > 0
            ? `, ${noGeomResult.cleaned} vechi șterse`
            : "";
        note =
          noGeomImported > 0
            ? `${noGeomImported} parcele noi fără geometrie importate${cleanedNote}`
            : `Nicio parcelă nouă fără geometrie${cleanedNote}`;
        pushProgress();
      }
      updatePhaseProgress(1, 1);
      finishPhase();
    }

    /* ══════════════════════════════════════════════════════════ */
    /*  Phase 2: Enrich (magic mode only)                        */
    /* ══════════════════════════════════════════════════════════ */
    // Take back progress control after syncLayer
    if (validated.mode === "magic") {
      setPhaseState("Verificare îmbogățire", weights.enrich, 1);

      const enrichStatus = await getLayerFreshness(
        validated.siruta,
        terenuriLayerId,
      );
      const needsEnrich =
        validated.forceSync ||
        enrichStatus.enrichedCount === 0 ||
        enrichStatus.enrichedCount < enrichStatus.featureCount;

      if (needsEnrich) {
        phase = "Îmbogățire parcele (CF, proprietari, adrese)";
        note = undefined;
        pushProgress();

        const client = await EterraClient.create(
          validated.username,
          validated.password,
          { timeoutMs: 120_000 },
        );

        await enrichFeatures(client, validated.siruta, {
          onProgress: (done, tot, ph) => {
            phase = ph;
            updatePhaseProgress(done, tot);
          },
        });
      } else {
        note = "Îmbogățire existentă — skip";
        pushProgress();
      }
      updatePhaseProgress(1, 1);
      finishPhase();
    }

    /* ══════════════════════════════════════════════════════════ */
    /*  Phase 3: Build GPKGs from local DB                       */
    /* ══════════════════════════════════════════════════════════ */
    setPhaseState("Generare GPKG din baza de date", weights.gpkg, 3);
    const srsWkt = getEpsg3844Wkt();

    // Load features from DB
    const dbTerenuri = await prisma.gisFeature.findMany({
      where: { layerId: terenuriLayerId, siruta: validated.siruta },
      select: {
        attributes: true,
        geometry: true,
        enrichment: true,
        geometrySource: true,
      },
    });

    const dbCladiri = await prisma.gisFeature.findMany({
      where: { layerId: cladiriLayerId, siruta: validated.siruta },
      select: { attributes: true, geometry: true },
    });

    // Convert DB records to GeoJSON features
    const toGeoFeatures = (
      records: { attributes: unknown; geometry: unknown }[],
    ): GeoJsonFeature[] =>
      records
        .filter((r) => r.geometry != null)
        .map((r) => ({
          type: "Feature" as const,
          geometry: r.geometry as GeoJsonFeature["geometry"],
          properties: r.attributes as Record<string, unknown>,
        }));

    const terenuriGeoFeatures = toGeoFeatures(dbTerenuri);
    const cladiriGeoFeatures = toGeoFeatures(dbCladiri);

    const terenuriFields =
      terenuriGeoFeatures.length > 0
        ? Object.keys(terenuriGeoFeatures[0]!.properties)
        : [];
    const cladiriFields =
      cladiriGeoFeatures.length > 0
        ? Object.keys(cladiriGeoFeatures[0]!.properties)
        : [];

    // GPKG terenuri
    const terenuriGpkg = await withHeartbeat(() =>
      buildGpkg({
        srsId: 3844,
        srsWkt,
        layers: [
          {
            name: "TERENURI_ACTIVE",
            fields: terenuriFields,
            features: terenuriGeoFeatures,
          },
        ],
      }),
    );
    updatePhaseProgress(1, 3);

    // GPKG cladiri
    const cladiriGpkg = await withHeartbeat(() =>
      buildGpkg({
        srsId: 3844,
        srsWkt,
        layers: [
          {
            name: "CLADIRI_ACTIVE",
            fields: cladiriFields,
            features: cladiriGeoFeatures,
          },
        ],
      }),
    );
    updatePhaseProgress(2, 3);

    // Magic: GPKG with enrichment + CSV
    let magicGpkg: Buffer | null = null;
    let csvContent: string | null = null;
    let hasBuildingCount = 0;
    let legalBuildingCount = 0;

    if (validated.mode === "magic") {
      // Build CSV
      const headers = [
        "OBJECTID",
        "IMMOVABLE_ID",
        "APPLICATION_ID",
        "NATIONAL_CADASTRAL_REFERENCE",
        "NR_CAD",
        "AREA_VALUE",
        "NR_CF",
        "NR_CF_VECHI",
        "NR_TOPO",
        "ADRESA",
        "PROPRIETARI",
        "PROPRIETARI_VECHI",
        "SUPRAFATA_2D",
        "SUPRAFATA_R",
        "SOLICITANT",
        "INTRAVILAN",
        "CATEGORIE_FOLOSINTA",
        "HAS_BUILDING",
        "BUILD_LEGAL",
        "HAS_GEOMETRY",
      ];
      const csvRows: string[] = [headers.map(csvEscape).join(",")];

      const magicFeatures: GeoJsonFeature[] = [];
      const magicFields = Array.from(
        new Set([
          ...terenuriFields,
          "NR_CAD",
          "NR_CF",
          "NR_CF_VECHI",
          "NR_TOPO",
          "ADRESA",
          "PROPRIETARI",
          "PROPRIETARI_VECHI",
          "SUPRAFATA_2D",
          "SUPRAFATA_R",
          "SOLICITANT",
          "INTRAVILAN",
          "CATEGORIE_FOLOSINTA",
          "HAS_BUILDING",
          "BUILD_LEGAL",
        ]),
      );

      for (const record of dbTerenuri) {
        const attrs = record.attributes as Record<string, unknown>;
        const enrichment =
          (record.enrichment as FeatureEnrichment | null) ??
          ({} as Partial<FeatureEnrichment>);
        const geom = record.geometry as GeoJsonFeature["geometry"];
        const geomSource = (
          record as unknown as { geometrySource: string | null }
        ).geometrySource;
        const hasGeometry =
          geom != null && geomSource !== "NO_GEOMETRY" ? 1 : 0;

        const e = enrichment as Partial<FeatureEnrichment>;
        if (Number(e.HAS_BUILDING ?? 0)) hasBuildingCount += 1;
        if (Number(e.BUILD_LEGAL ?? 0)) legalBuildingCount += 1;

        const row = [
          attrs.OBJECTID ?? "",
          attrs.IMMOVABLE_ID ?? "",
          attrs.APPLICATION_ID ?? "",
          attrs.NATIONAL_CADASTRAL_REFERENCE ?? "",
          e.NR_CAD ?? "",
          attrs.AREA_VALUE ?? "",
          e.NR_CF ?? "",
          e.NR_CF_VECHI ?? "",
          e.NR_TOPO ?? "",
          e.ADRESA ?? "",
          e.PROPRIETARI ?? "",
          e.PROPRIETARI_VECHI ?? "",
          e.SUPRAFATA_2D ?? "",
          e.SUPRAFATA_R ?? "",
          e.SOLICITANT ?? "",
          e.INTRAVILAN ?? "",
          e.CATEGORIE_FOLOSINTA ?? "",
          e.HAS_BUILDING ?? 0,
          e.BUILD_LEGAL ?? 0,
          hasGeometry,
        ];
        csvRows.push(row.map(csvEscape).join(","));

        // ALL records go into magic GPKG — with or without geometry
        magicFeatures.push({
          type: "Feature",
          geometry: geom,
          properties: { ...attrs, ...e, HAS_GEOMETRY: hasGeometry },
        });
      }

      csvContent = csvRows.join("\n");

      magicGpkg = await withHeartbeat(() =>
        buildGpkg({
          srsId: 3844,
          srsWkt,
          layers: [
            {
              name: "TERENURI_MAGIC",
              fields: [...magicFields, "HAS_GEOMETRY"],
              features: magicFeatures,
              includeNullGeometry: true,
            },
          ],
        }),
      );
    }
    updatePhaseProgress(3, 3);
    finishPhase();

    /* ══════════════════════════════════════════════════════════ */
    /*  Phase 4: ZIP                                             */
    /* ══════════════════════════════════════════════════════════ */
    setPhaseState("Comprimare ZIP", weights.zip, 1);
    const zip = new JSZip();
    zip.file("terenuri.gpkg", terenuriGpkg);
    zip.file("cladiri.gpkg", cladiriGpkg);

    // DXF versions (non-fatal)
    try {
      const { gpkgToDxf } = await import(
        "@/modules/parcel-sync/services/gpkg-export"
      );
      const tDxf = await gpkgToDxf(terenuriGpkg, "TERENURI_ACTIVE");
      if (tDxf) zip.file("terenuri.dxf", tDxf);
      const cDxf = await gpkgToDxf(cladiriGpkg, "CLADIRI_ACTIVE");
      if (cDxf) zip.file("cladiri.dxf", cDxf);
    } catch {
      // DXF conversion not available — skip silently
    }

    // ── Comprehensive quality analysis ──
    const withGeomRecords = dbTerenuri.filter(
      (r) =>
        (r as unknown as { geometrySource: string | null }).geometrySource !==
        "NO_GEOMETRY",
    );
    const noGeomRecords = dbTerenuri.filter(
      (r) =>
        (r as unknown as { geometrySource: string | null }).geometrySource ===
        "NO_GEOMETRY",
    );

    const analyzeRecords = (records: typeof dbTerenuri) => {
      let enriched = 0;
      let withOwners = 0;
      let withOldOwners = 0;
      let withCF = 0;
      let withAddress = 0;
      let withArea = 0;
      let withCategory = 0;
      let withBuilding = 0;
      let complete = 0;
      let partial = 0;
      let empty = 0;

      for (const r of records) {
        const e = r.enrichment as Record<string, unknown> | null;
        if (!e) {
          empty++;
          continue;
        }
        enriched++;
        const hasOwners = !!e.PROPRIETARI && e.PROPRIETARI !== "-";
        const hasOldOwners =
          !!e.PROPRIETARI_VECHI && String(e.PROPRIETARI_VECHI).trim() !== "";
        const hasCF = !!e.NR_CF && e.NR_CF !== "-";
        const hasAddr = !!e.ADRESA && e.ADRESA !== "-";
        const hasArea =
          e.SUPRAFATA_2D != null &&
          e.SUPRAFATA_2D !== "" &&
          Number(e.SUPRAFATA_2D) > 0;
        const hasCat = !!e.CATEGORIE_FOLOSINTA && e.CATEGORIE_FOLOSINTA !== "-";
        const hasBuild = Number(e.HAS_BUILDING ?? 0) === 1;

        if (hasOwners) withOwners++;
        if (hasOldOwners) withOldOwners++;
        if (hasCF) withCF++;
        if (hasAddr) withAddress++;
        if (hasArea) withArea++;
        if (hasCat) withCategory++;
        if (hasBuild) withBuilding++;

        // "Complete" = has at least owners + CF + area
        if (hasOwners && hasCF && hasArea) complete++;
        else if (hasOwners || hasCF || hasAddr || hasArea || hasCat) partial++;
        else empty++;
      }

      return {
        total: records.length,
        enriched,
        withOwners,
        withOldOwners,
        withCF,
        withAddress,
        withArea,
        withCategory,
        withBuilding,
        complete,
        partial,
        empty,
      };
    };

    const qualityAll = analyzeRecords(dbTerenuri);
    const qualityGeom = analyzeRecords(withGeomRecords);
    const qualityNoGeom = analyzeRecords(noGeomRecords);

    const report: Record<string, unknown> = {
      siruta: validated.siruta,
      generatedAt: new Date().toISOString(),
      source: "local-db (sync-first)",
      pipeline: {
        syncedGis: {
          terenuri: terenuriNeedsSync ? "descărcat" : "din cache",
          cladiri: cladiriNeedsSync ? "descărcat" : "din cache",
        },
        noGeometry: hasNoGeom
          ? {
              imported: noGeomImported,
              cleaned: noGeomCleaned,
              skipped: noGeomSkipped,
            }
          : "dezactivat",
        enriched: validated.mode === "magic" ? "da" : "nu",
        finalDb: {
          total: dbTerenuri.length,
          withGeometry: withGeomRecords.length,
          noGeometry: noGeomRecords.length,
          cladiri: cladiriGeoFeatures.length,
        },
      },
      terenuri: {
        count: terenuriGeoFeatures.length,
        totalInDb: dbTerenuri.length,
        noGeometryCount: noGeomRecords.length,
      },
      cladiri: { count: cladiriGeoFeatures.length },
      syncSkipped: {
        terenuri: !terenuriNeedsSync,
        cladiri: !cladiriNeedsSync,
      },
      includeNoGeometry: hasNoGeom,
      noGeomImported,
      qualityAnalysis: {
        all: qualityAll,
        withGeometry: qualityGeom,
        noGeometry: qualityNoGeom,
      },
    };

    if (validated.mode === "magic" && magicGpkg && csvContent) {
      zip.file("terenuri_magic.gpkg", magicGpkg);
      try {
        const { gpkgToDxf } = await import(
          "@/modules/parcel-sync/services/gpkg-export"
        );
        const mDxf = await gpkgToDxf(magicGpkg, "TERENURI_MAGIC");
        if (mDxf) zip.file("terenuri_magic.dxf", mDxf);
      } catch {
        // DXF conversion not available
      }
      zip.file("terenuri_complet.csv", csvContent);
      report.magic = {
        csvRows: csvContent.split("\n").length - 1,
        hasBuildingCount,
        legalBuildingCount,
      };

      // Generate human-readable quality report (Romanian)
      const pct = (n: number, total: number) =>
        total > 0 ? `${((n / total) * 100).toFixed(1)}%` : "0%";
      const fmt = (n: number) => n.toLocaleString("ro-RO");

      const lines: string[] = [
        `══════════════════════════════════════════════════════════`,
        `  RAPORT CALITATE DATE — UAT SIRUTA ${validated.siruta}`,
        `  Generat: ${new Date().toISOString().replace("T", " ").slice(0, 19)}`,
        `══════════════════════════════════════════════════════════`,
        ``,
        `PIPELINE — CE S-A ÎNTÂMPLAT`,
        `─────────────────────────────────────────────────────────`,
        `  1. Sync GIS terenuri:         ${terenuriNeedsSync ? "descărcat din eTerra" : "din cache local (date proaspete)"}`,
        `  2. Sync GIS clădiri:          ${cladiriNeedsSync ? "descărcat din eTerra" : "din cache local (date proaspete)"}`,
        ...(hasNoGeom
          ? [
              `  3. Import fără geometrie:     ${fmt(noGeomImported)} noi importate` +
                (noGeomCleaned > 0
                  ? `, ${fmt(noGeomCleaned)} vechi șterse`
                  : "") +
                (noGeomSkipped > 0
                  ? `, ${fmt(noGeomSkipped)} filtrate/skip`
                  : ""),
            ]
          : [`  3. Import fără geometrie:     dezactivat`]),
        `  4. Îmbogățire (CF, prop.):    da`,
        `  5. Generare fișiere:          GPKG + CSV + raport`,
        ``,
        `STARE FINALĂ BAZĂ DE DATE`,
        `─────────────────────────────────────────────────────────`,
        `  Total parcele în baza de date:    ${fmt(dbTerenuri.length)}`,
        `    • Cu geometrie (contur GIS):    ${fmt(withGeomRecords.length)}`,
        `    • Fără geometrie (doar date):   ${fmt(noGeomRecords.length)}`,
        `  Clădiri:                          ${fmt(cladiriGeoFeatures.length)}`,
        ``,
        `CALITATE ÎMBOGĂȚIRE — TOATE PARCELELE (${fmt(qualityAll.total)})`,
        `─────────────────────────────────────────────────────────`,
        `  Îmbogățite:        ${fmt(qualityAll.enriched)} (${pct(qualityAll.enriched, qualityAll.total)})`,
        `  Cu proprietari:    ${fmt(qualityAll.withOwners)} (${pct(qualityAll.withOwners, qualityAll.total)})`,
        `  Cu prop. vechi:    ${fmt(qualityAll.withOldOwners)} (${pct(qualityAll.withOldOwners, qualityAll.total)})`,
        `  Cu nr. CF:         ${fmt(qualityAll.withCF)} (${pct(qualityAll.withCF, qualityAll.total)})`,
        `  Cu adresă:         ${fmt(qualityAll.withAddress)} (${pct(qualityAll.withAddress, qualityAll.total)})`,
        `  Cu suprafață:      ${fmt(qualityAll.withArea)} (${pct(qualityAll.withArea, qualityAll.total)})`,
        `  Cu categorie fol.: ${fmt(qualityAll.withCategory)} (${pct(qualityAll.withCategory, qualityAll.total)})`,
        `  Cu clădire:        ${fmt(qualityAll.withBuilding)} (${pct(qualityAll.withBuilding, qualityAll.total)})`,
        `  ────────────────`,
        `  Complete (prop+CF+sup): ${fmt(qualityAll.complete)} (${pct(qualityAll.complete, qualityAll.total)})`,
        `  Parțiale:              ${fmt(qualityAll.partial)} (${pct(qualityAll.partial, qualityAll.total)})`,
        `  Goale (fără date):     ${fmt(qualityAll.empty)} (${pct(qualityAll.empty, qualityAll.total)})`,
        ``,
      ];

      if (withGeomRecords.length > 0) {
        lines.push(
          `PARCELE CU GEOMETRIE (${fmt(qualityGeom.total)})`,
          `─────────────────────────────────────────────────────────`,
          `  Îmbogățite:        ${fmt(qualityGeom.enriched)} (${pct(qualityGeom.enriched, qualityGeom.total)})`,
          `  Cu proprietari:    ${fmt(qualityGeom.withOwners)} (${pct(qualityGeom.withOwners, qualityGeom.total)})`,
          `  Cu nr. CF:         ${fmt(qualityGeom.withCF)} (${pct(qualityGeom.withCF, qualityGeom.total)})`,
          `  Cu adresă:         ${fmt(qualityGeom.withAddress)} (${pct(qualityGeom.withAddress, qualityGeom.total)})`,
          `  Cu suprafață:      ${fmt(qualityGeom.withArea)} (${pct(qualityGeom.withArea, qualityGeom.total)})`,
          `  Cu categorie fol.: ${fmt(qualityGeom.withCategory)} (${pct(qualityGeom.withCategory, qualityGeom.total)})`,
          `  Complete:          ${fmt(qualityGeom.complete)} (${pct(qualityGeom.complete, qualityGeom.total)})`,
          `  Parțiale:          ${fmt(qualityGeom.partial)} (${pct(qualityGeom.partial, qualityGeom.total)})`,
          `  Goale:             ${fmt(qualityGeom.empty)} (${pct(qualityGeom.empty, qualityGeom.total)})`,
          ``,
        );
      }

      if (noGeomRecords.length > 0) {
        lines.push(
          `PARCELE FĂRĂ GEOMETRIE (${fmt(qualityNoGeom.total)})`,
          `─────────────────────────────────────────────────────────`,
          `  Îmbogățite:        ${fmt(qualityNoGeom.enriched)} (${pct(qualityNoGeom.enriched, qualityNoGeom.total)})`,
          `  Cu proprietari:    ${fmt(qualityNoGeom.withOwners)} (${pct(qualityNoGeom.withOwners, qualityNoGeom.total)})`,
          `  Cu nr. CF:         ${fmt(qualityNoGeom.withCF)} (${pct(qualityNoGeom.withCF, qualityNoGeom.total)})`,
          `  Cu adresă:         ${fmt(qualityNoGeom.withAddress)} (${pct(qualityNoGeom.withAddress, qualityNoGeom.total)})`,
          `  Cu suprafață:      ${fmt(qualityNoGeom.withArea)} (${pct(qualityNoGeom.withArea, qualityNoGeom.total)})`,
          `  Cu categorie fol.: ${fmt(qualityNoGeom.withCategory)} (${pct(qualityNoGeom.withCategory, qualityNoGeom.total)})`,
          `  Complete:          ${fmt(qualityNoGeom.complete)} (${pct(qualityNoGeom.complete, qualityNoGeom.total)})`,
          `  Parțiale:          ${fmt(qualityNoGeom.partial)} (${pct(qualityNoGeom.partial, qualityNoGeom.total)})`,
          `  Goale:             ${fmt(qualityNoGeom.empty)} (${pct(qualityNoGeom.empty, qualityNoGeom.total)})`,
          ``,
        );
      }

      lines.push(
        `NOTE`,
        `─────────────────────────────────────────────────────────`,
        `  • "Complete" = are proprietari + nr. CF + suprafață`,
        `  • "Parțiale" = are cel puțin un câmp util`,
        `  • "Goale" = niciun câmp de îmbogățire completat`,
        `  • Parcelele fără geometrie provin din lista de imobile`,
        `    eTerra și nu au contur desenat în layerul GIS.`,
        `  • Datele sunt extrase din ANCPI eTerra la data raportului.`,
        `══════════════════════════════════════════════════════════`,
      );

      zip.file("raport_calitate.txt", lines.join("\n"));
    }
    zip.file("export_report.json", JSON.stringify(report, null, 2));

    const zipBuffer = await withHeartbeat(() =>
      zip.generateAsync({ type: "nodebuffer", compression: "STORE" }),
    );
    updatePhaseProgress(1, 1);
    finishPhase();

    /* Done */
    const noGeomInDb = noGeomRecords.length;
    message = `Finalizat 100% · Terenuri ${terenuriGeoFeatures.length} · Clădiri ${cladiriGeoFeatures.length}`;
    if (noGeomInDb > 0) {
      message += ` · Fără geometrie ${noGeomInDb}`;
    }
    if (!terenuriNeedsSync && !cladiriNeedsSync) {
      message += " (din cache local)";
    }
    // Quality summary in note (visible in UI progress card)
    if (validated.mode === "magic") {
      const qParts: string[] = [];
      qParts.push(`Complete: ${qualityAll.complete}/${qualityAll.total}`);
      if (qualityAll.partial > 0)
        qParts.push(`parțiale: ${qualityAll.partial}`);
      if (qualityAll.empty > 0) qParts.push(`goale: ${qualityAll.empty}`);
      qParts.push(`prop: ${qualityAll.withOwners}`);
      qParts.push(`CF: ${qualityAll.withCF}`);
      qParts.push(`sup: ${qualityAll.withArea}`);
      note = `Calitate: ${qParts.join(" · ")} — vezi raport_calitate.txt în ZIP`;
    }
    status = "done";
    phase = "Finalizat";
    // note already set with quality summary above (or undefined for base mode)
    pushProgress();
    scheduleClear(jobId);

    const filename =
      validated.mode === "magic"
        ? `eterra_uat_${validated.siruta}_magic.zip`
        : `eterra_uat_${validated.siruta}_terenuri_cladiri.zip`;
    if (jobId) unregisterJob(jobId);
    return new Response(new Uint8Array(zipBuffer), {
      headers: {
        "Content-Type": "application/zip",
        "Content-Disposition": `attachment; filename="${filename}"`,
      },
    });
  } catch (error) {
    const errMessage =
      error instanceof Error ? error.message : "Unexpected server error";
    status = "error";
    message = errMessage;
    note = undefined;
    pushProgress();
    scheduleClear(jobId);
    if (jobId) unregisterJob(jobId);
    const lower = errMessage.toLowerCase();
    const statusCode =
      lower.includes("login failed") || lower.includes("session") ? 401 : 400;
    return new Response(JSON.stringify({ error: errMessage }), {
      status: statusCode,
      headers: { "Content-Type": "application/json" },
    });
  }
}
