

import "./pwdjhucdpxshwlujddqk/lfsbuoyopvkcqdpeputxelsaiapjsu.mjs";
import { createServer } from "node:http";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { access, lstat, mkdir, mkdtemp, readdir, readFile, rm, stat, unlink, writeFile } from "node:fs/promises";
import { constants as fsConstants, createReadStream, createWriteStream } from "node:fs";
import { dirname, extname, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { spawn } from "node:child_process";
import { createGeneraliAutomation } from "./pwdjhucdpxshwlujddqk/ysfgsnpenrkknlwjevdrklazxljpihx.mjs";
import { createMtuAutomation, validateMtuCredentials } from "./pwdjhucdpxshwlujddqk/ptxmpkztgntfuqeg.mjs";
import { createHestiaAutomation, validateHestiaCredentials } from "./pwdjhucdpxshwlujddqk/smfhozvelxisesrntwwiirarccp.mjs";
import { createTrastiAutomation } from "./pwdjhucdpxshwlujddqk/pxuttfeiirbybgavssemctewvwigzd.mjs";
import { createWienerAutomation } from "./pwdjhucdpxshwlujddqk/wcjwkazzizmaexpinwryjeopvruz.mjs";
import { createCompensaAutomation } from "./pwdjhucdpxshwlujddqk/ccycczfofkqmogwgpfbecqnshkspxwyaotlv.mjs";
import { createBrowserPool } from "./pwdjhucdpxshwlujddqk/wfsrzwmiudpskgbaihta.mjs";
import { createAllianzAutomation } from "./pwdjhucdpxshwlujddqk/nqfyagubklpuluueifwtpaqytmnenzngow.mjs";
import { createWartaAutomation, wartaPathIncludesRecordSelection } from "./pwdjhucdpxshwlujddqk/ggwdzafafrvmrhsltsmabprw.mjs";
import { createPzuAutomation } from "./pwdjhucdpxshwlujddqk/wrpdqznfyuoa.mjs";
import { createInslyAutomation, normalizeInslyPdfPolicyKey } from "./pwdjhucdpxshwlujddqk/leqwiamnvzqsyslrapyduqz.mjs";
import { createCredentialVault } from "./pwdjhucdpxshwlujddqk/pgaspyqkejxcmlrcfdbeltxttgjisgydu.mjs";
import { createPortableRouteStore } from "./pwdjhucdpxshwlujddqk/jqhtrnuomauidxtqjxexpsuqtjyaooqnmyrnwzezi.mjs";
import { createPortfolioImportState } from "./pwdjhucdpxshwlujddqk/ugbqajgadibesxswlusl.mjs";
import {
  assertPortfolioEmissionReport,
  assertPortfolioMappingComplete,
  PORTFOLIO_EMISSION_FULL_COVERAGE,
  PORTFOLIO_EMISSION_INCREMENTAL_COVERAGE,
  PORTFOLIO_EMISSION_PDF_BACKLOG_ONLY_COVERAGE,
  PORTFOLIO_MAPPING_PDF_BACKLOG_ONLY_COVERAGE,
} from "./pwdjhucdpxshwlujddqk/fgroazrhswhewnaqxvgl.mjs";
import {
  createPortfolioImportReviewStore,
  createPortfolioIssueIdentityHash,
} from "./pwdjhucdpxshwlujddqk/xombeztlyiegtybxtzkg.mjs";
import {
  createKontoStore,
  formatAgencyPairingCode,
  normalizeAccountId,
} from "./pwdjhucdpxshwlujddqk/vycskrvnsorinpoytkcfcoiswsdectqjogvrxwenlni.mjs";
import {
  buildEmployeePackage,
  buildCentralPackage,
  buildEmployeeAssignmentPackage,
  PACKAGE_MAX_UPLOAD_BYTES,
  PackageValidationError,
  preflightCentralPackageArchive,
  validateExtractedCentralPackage,
  validateExtractedEmployeeAssignmentPackage,
} from "./pwdjhucdpxshwlujddqk/ifxgzldrlyxlpaactmkx.mjs";
import {
  createEmployeePackageImportTransactionStore,
  PackageImportTransactionError,
} from "./pwdjhucdpxshwlujddqk/uutkwvuoermosbzjabjy.mjs";
import {
  createEmployeeAssignmentImportTransactionStore,
} from "./pwdjhucdpxshwlujddqk/nqnguiloekwexnajrdoc.mjs";
import { createTrainingDiagnosticsStore } from "./pwdjhucdpxshwlujddqk/uukgjwtwzjhojgnvquls.mjs";
import { createDiagnostykaStore } from "./pwdjhucdpxshwlujddqk/aquxmpfhjyorgygfwoch.mjs";
import { createUpdateService, isLicencjaError } from "./pwdjhucdpxshwlujddqk/gkdioujebaycybehvkls.mjs";
import { createLicencjaStore } from "./pwdjhucdpxshwlujddqk/swtdxqahsfhdiakofych.mjs";
import { createLicencjaProgramu } from "./pwdjhucdpxshwlujddqk/zzlghzujvhtqsqmltpqf.mjs";
import { createAnswerStore, normalizeAnswerLabel } from "./pwdjhucdpxshwlujddqk/iayvgxmcphfydptinkse.mjs";
import { buildVehicleTechnicalAnswerResolver, composeKnownAnswerResolvers } from "./pwdjhucdpxshwlujddqk/etrzxtbsmrmtpfpyetfs.mjs";
import {
  extractVehicleDataFromFormAnswers,
  mergeVehicleDataWithSource,
} from "./pwdjhucdpxshwlujddqk/ionzpdrwzlfyluehmlkj.mjs";
import {
  czyZaszyfrowany as czyZaszyfrowanaBaza,
  migrujPlikiBazyDoSzyfru,
  normalizujKluczRatunkowy,
  odszyfrujBufor as odszyfrujBuforBazy,
  utworzSzyfrBazy,
} from "./pwdjhucdpxshwlujddqk/jvllscdeiznoyurocfkxrrcaablneamaszqbgyas.mjs";
import { createPolicyPdfReader } from "./pwdjhucdpxshwlujddqk/coczkfzfvygnlgtstaonmcriqqkyxcqpdybdsglfvx.mjs";
import {
  pobierzDaneZHistoriiPojazdu,
  walidujZapytanieHistorii,
} from "./pwdjhucdpxshwlujddqk/dzcorprbwbuulnqoqjgs.mjs";
import { pipeStreamToHttpResponse } from "./pwdjhucdpxshwlujddqk/oyelwxxpvlayzkbedxmd.mjs";
import {
  createPortfolioPdfIdentity,
  createPortfolioPdfRetryStore,
  normalizePortfolioPdfInsurer,
} from "./pwdjhucdpxshwlujddqk/ldpwrbpjqvuxzylkmjve.mjs";
import {
  cleanupPortfolioPdfJobDirectory,
  createPortfolioPdfJobDirectory,
  serializePortfolioPdfRetryStatus,
  sweepOrphanedPortfolioPdfJobDirectories,
  validatePortfolioPdfJobDirectory,
} from "./pwdjhucdpxshwlujddqk/kkclsmcmnrxnrwqlbzik.mjs";
import {
  createSafeSerialQueue,
  getJobTimeoutMs,
  runWithDeadline,
} from "./pwdjhucdpxshwlujddqk/ufmwopolrnsrfsheeckx.mjs";

const FILES_DIRECTORY = dirname(fileURLToPath(import.meta.url));
const ROOT_DIRECTORY = dirname(FILES_DIRECTORY);
const HOST = "127.0.0.1";
const PORT = Number.parseInt(process.env.BAZA_POLIS_PORT || "3210", 10);
const APP_ORIGIN = `http://${HOST}:${PORT}`;
const APP_URL = `${APP_ORIGIN}/start.htm`;

const ALLOWED_REQUEST_HOSTS = new Set([`${HOST}:${PORT}`, `localhost:${PORT}`]);


const UPDATE_BASE_URL = "https://licencje.iseka.pl/aktualizacje/";
const MAX_REQUEST_BODY = 32 * 1024;


const MAX_PORTFOLIO_REQUEST_BODY = 256 * 1024;
const JOB_RETENTION_MS = 30 * 60 * 1000;
const SHUTDOWN_FORCE_EXIT_MS = 3000;
const SHUTDOWN_CLOSE_TIMEOUT_MS = 2000;
const CHROME_CANDIDATES = [
  "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
  process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe") : "",
].filter(Boolean);

const CONTENT_TYPES = new Map([
  [".htm", "text/html; charset=utf-8"],
  [".html", "text/html; charset=utf-8"],
  [".js", "text/javascript; charset=utf-8"],
  [".mjs", "text/javascript; charset=utf-8"],
  [".css", "text/css; charset=utf-8"],
  [".json", "application/json; charset=utf-8"],
  [".pdf", "application/pdf"],
  [".ico", "image/x-icon"],
  [".png", "image/png"],
  [".jpg", "image/jpeg"],
  [".jpeg", "image/jpeg"],
  [".webp", "image/webp"],
  [".svg", "image/svg+xml"],
  [".ttf", "font/ttf"],
  [".txt", "text/plain; charset=utf-8"],
]);
const PUBLIC_FILES = new Set([
  "start.htm",
  "pliki/mrmuaiqdpzjowpihiz.js",
  "pliki/kkpybpmhonxogbwetgp.js",
  "pliki/pbvcrbtheayxdibsiziopspjvliemamswmymzletxoiriwob.js",
  "pliki/wwpfromllxxaibsmcggeilaesdhsxnfpjbkdhvfzn.js",
  "pliki/rsoboqwptvhomquiafjt.js",
  "pliki/vrjeksrdppugqlwzhfab.js",
  "pliki/xrhckdwhwcdxzqgbexgi.js",
  "pliki/vhwsorwqtxdyzietldhegbsptp.css",
  "pliki/ycsqctiwsleqkdjoimum.js",
  "pliki/wypowiedzenieocdruk.pdf",
  "pliki/wypowiedzenieautomat.pdf",
  "pliki/wypowiedzenienabywcy.pdf",
  
  
  "pliki/wersja-aplikacji.json",
]);
const PUBLIC_DIRECTORIES = [
  "pliki/assets/",
  "pliki/fonts/",
  "pliki/vzhgqyjhppnpobjprzyl/",
  "pliki/routetu/",
  "pliki/tools/",
  "pliki/vendor/",
];

async function odczytajMotywStartowy() {
  try {
    const ustawienia = JSON.parse(
      await readFile(join(ROOT_DIRECTORY, "polisy-ustawienia.json"), "utf8"),
    );
    return ustawienia?.theme === "dark" || ustawienia?.theme === "light"
      ? ustawienia.theme
      : "";
  } catch {
    return "";
  }
}

const jobs = new Map();
const cancelledQuoteBatchIds = new Map();
const QUOTE_BATCH_CANCELLATION_TTL_MS = 2 * 60 * 60 * 1000;
let shuttingDown = false;

function normalizeClientQuoteBatchId(value) {
  const batchId = String(value || "").trim();
  return /^[a-z0-9][a-z0-9-]{7,79}$/i.test(batchId) ? batchId.toLowerCase() : "";
}

function pruneCancelledQuoteBatchIds(now = Date.now()) {
  for (const [batchId, cancelledAt] of cancelledQuoteBatchIds) {
    if (now - cancelledAt > QUOTE_BATCH_CANCELLATION_TTL_MS) {
      cancelledQuoteBatchIds.delete(batchId);
    }
  }
}

function markQuoteBatchCancelled(batchId) {
  const normalizedBatchId = normalizeClientQuoteBatchId(batchId);
  if (!normalizedBatchId) return "";
  const now = Date.now();
  pruneCancelledQuoteBatchIds(now);
  cancelledQuoteBatchIds.set(normalizedBatchId, now);
  return normalizedBatchId;
}

function isQuoteBatchCancelled(batchId) {
  const normalizedBatchId = normalizeClientQuoteBatchId(batchId);
  if (!normalizedBatchId) return false;
  pruneCancelledQuoteBatchIds();
  return cancelledQuoteBatchIds.has(normalizedBatchId);
}















let portfolioImportTurn = Promise.resolve();
let portfolioImportsInFlight = 0;
let quoteJobsInFlight = 0;
let openQuoteGeneration = null;

function createQuoteGeneration() {
  let resolveDrained;
  return {
    count: 0,
    sealed: false,
    drained: new Promise((resolve) => { resolveDrained = resolve; }),
    resolveDrained,
  };
}

function reservePortfolioImportTurn(job) {
  const previousTurn = portfolioImportTurn;
  const quoteGeneration = openQuoteGeneration?.sealed === false
    ? openQuoteGeneration
    : null;
  if (quoteGeneration) quoteGeneration.sealed = true;
  const quotesBeforeTurn = quoteGeneration?.drained || Promise.resolve();
  let finishTurn;
  portfolioImportTurn = new Promise((resolve) => { finishTurn = resolve; });
  if (portfolioImportsInFlight > 0) {
    updateJob(job, {
      status: "queued",
      title: "Oczekiwanie na inny import…",
      detail: "Importy uruchamiają się pojedynczo. Ten rozpocznie się automatycznie po zakończeniu poprzedniego.",
    });
  }
  portfolioImportsInFlight += 1;
  
  
  
  let turnReleaseRequested = false;
  let turnReleased = false;
  let turnStarted = false;
  let releasePromise = null;
  const releaseTurn = () => {
    if (releasePromise) return releasePromise;
    turnReleaseRequested = true;
    releasePromise = (async () => {
      await previousTurn;
      await quotesBeforeTurn;
      
      
      const closeAttempt = job?.importTurnReleaseBarrier;
      if (closeAttempt && typeof closeAttempt.then === "function") {
        await closeAttempt.catch(() => {});
      }
      if (turnReleased) return;
      turnReleased = true;
      portfolioImportsInFlight = Math.max(0, portfolioImportsInFlight - 1);
      finishTurn();
    })();
    return releasePromise;
  };
  if (job && typeof job === "object") job.releaseImportTurn = releaseTurn;

  async function runReserved(run) {
    turnStarted = true;
    try {
      await previousTurn;
      if (!turnReleased && quoteGeneration?.count > 0) {
        updateJob(job, {
          status: "queued",
          title: "Oczekiwanie na zakończenie kalkulacji…",
          detail: "Trwa liczenie składki. Import rozpocznie się automatycznie po jego zakończeniu.",
        });
        await quotesBeforeTurn;
      }
      
      
      if (await kontoStore.isEmployeeMode()) {
        throw new Error("Pobieranie polis z towarzystw jest dostępne tylko w bazie głównej agencji.");
      }
      
      
      if (turnReleaseRequested || job?.watchdogExpired === true) {
        throw createJobGuardError("JOB_CANCELLED");
      }
      return await run();
    } finally {
      if (job && typeof job === "object" && job.releaseImportTurn === releaseTurn) {
        delete job.releaseImportTurn;
      }
      await releaseTurn();
      if (job && typeof job === "object") {
        delete job.importTurnReleaseBarrier;
      }
    }
  }

  return Object.freeze({
    run: runReserved,
    release: releaseTurn,
    hasStarted: () => turnStarted,
  });
}

function reserveQuoteTurn(job) {
  const importsBeforeQuote = portfolioImportTurn;
  const hadImportsBeforeQuote = portfolioImportsInFlight > 0;
  if (!openQuoteGeneration || openQuoteGeneration.sealed) {
    openQuoteGeneration = createQuoteGeneration();
  }
  const generation = openQuoteGeneration;
  generation.count += 1;
  quoteJobsInFlight += 1;
  let released = false;
  let started = false;
  let releasePromise = null;

  const releaseQuote = () => {
    if (releasePromise) return releasePromise;
    releasePromise = (async () => {
      const closeAttempt = job?.importTurnReleaseBarrier;
      if (closeAttempt && typeof closeAttempt.then === "function") {
        await closeAttempt.catch(() => {});
      }
      if (released) return;
      released = true;
      generation.count = Math.max(0, generation.count - 1);
      quoteJobsInFlight = Math.max(0, quoteJobsInFlight - 1);
      if (generation.count === 0) {
        generation.resolveDrained();
        if (openQuoteGeneration === generation) openQuoteGeneration = null;
      }
    })();
    return releasePromise;
  };
  if (job && typeof job === "object") job.releaseQuoteTurn = releaseQuote;

  async function runReserved(run) {
    started = true;
    try {
      if (hadImportsBeforeQuote) {
        updateJob(job, {
          status: "queued",
          title: "Oczekiwanie na zakończenie importu…",
          detail: "Trwa pobieranie polis. Kalkulacja rozpocznie się automatycznie po jego zakończeniu.",
        });
      }
      
      
      await importsBeforeQuote;
      if (job?.watchdogExpired === true || TERMINAL_JOB_STATUSES.has(job?.status)) {
        throw createJobGuardError("JOB_CANCELLED");
      }
      return await run();
    } finally {
      if (job && typeof job === "object" && job.releaseQuoteTurn === releaseQuote) {
        delete job.releaseQuoteTurn;
      }
      await releaseQuote();
      if (job && typeof job === "object") {
        delete job.importTurnReleaseBarrier;
      }
    }
  }

  return Object.freeze({
    run: runReserved,
    release: releaseQuote,
    hasStarted: () => started,
  });
}

async function runWithPortfolioImportTurn(job, run, reservation = null) {
  return (reservation || reservePortfolioImportTurn(job)).run(run);
}

async function runWithQuoteTurn(job, run, reservation = null) {
  return (reservation || reserveQuoteTurn(job)).run(run);
}







function drawPdfPolicyLimit() {
  return 100000;
}



const portfolioPdfRetryStore = createPortfolioPdfRetryStore({
  storagePath: join(ROOT_DIRECTORY, "polisy-pdf-retry.json"),
});

async function findChromeExecutable() {
  for (const candidate of CHROME_CANDIDATES) {
    try {
      await access(candidate, fsConstants.X_OK);
      return candidate;
    } catch {
    }
  }
  return "";
}

const chromeExecutablePath = await findChromeExecutable();


const browserPool = createBrowserPool({
  chromeExecutablePath,
  profilesDirectory: join(FILES_DIRECTORY, "tmp"),
});
const wartaAutomation = createWartaAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const generaliAutomation = createGeneraliAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const mtuAutomation = createMtuAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const hestiaAutomation = createHestiaAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const trastiAutomation = createTrastiAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const wienerAutomation = createWienerAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const compensaAutomation = createCompensaAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const allianzAutomation = createAllianzAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const pzuAutomation = createPzuAutomation({
  browserPool,
  pdfRetryStore: portfolioPdfRetryStore,
});
const inslyAutomation = createInslyAutomation({
  browserPool,
});
const automationByInsurerId = new Map([
  ["generali", generaliAutomation],
  ["mtu", mtuAutomation],
  ["hestia", hestiaAutomation],
  ["trasti", trastiAutomation],
  ["wiener", wienerAutomation],
  ["compensa", compensaAutomation],
  ["allianz", allianzAutomation],
  ["warta", wartaAutomation],
  ["pzu", pzuAutomation],
  ["insly", inslyAutomation],
]);
const generaliQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const mtuQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const hestiaQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const trastiQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const wienerQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const compensaQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const allianzQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const wartaQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const pzuQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});
const inslyQueue = createSafeSerialQueue({
  onRejected: (error, context) => handleAutomationJobRejection(error, context),
});


const automationQueueByInsurerId = new Map([
  ["generali", generaliQueue],
  ["mtu", mtuQueue],
  ["hestia", hestiaQueue],
  ["trasti", trastiQueue],
  ["wiener", wienerQueue],
  ["compensa", compensaQueue],
  ["allianz", allianzQueue],
  ["warta", wartaQueue],
  ["pzu", pzuQueue],
  ["insly", inslyQueue],
]);
const credentialVault = createCredentialVault({
  storageDirectory: join(FILES_DIRECTORY, "tmp", "secrets"),
});
await credentialVault.deleteLegacyWartaRecordSelection().catch(() => {});




const szyfrBazy = utworzSzyfrBazy({ rootDirectory: ROOT_DIRECTORY });
let szyfrInitBezAwarii = true;
try {
  await szyfrBazy.init();
} catch (error) {
  
  
  
  
  szyfrInitBezAwarii = false;
  szyfrBazy.oznaczOczekiwanieNaRatunkowy();
  console.error("Szyfr bazy: nie udało się odczytać pliku klucza.", error?.message || error);
}
if (szyfrInitBezAwarii) {
  if (szyfrBazy.stan() === "brak") {
    
    
    for (const fileName of ["polisy-dane.json", "polisy-odpowiedzi.json"]) {
      const bytes = await readFile(join(ROOT_DIRECTORY, fileName)).catch(() => null);
      if (bytes && czyZaszyfrowanaBaza(bytes)) {
        szyfrBazy.oznaczOczekiwanieNaRatunkowy();
        break;
      }
    }
  }
  await szyfrBazy.utworzKluczJesliBrak();
  
  
  
  await szyfrBazy.sprawdzZgodnoscZBaza(join(ROOT_DIRECTORY, "polisy-dane.json"));
  if (szyfrBazy.aktywny()) {
    try {
      const wynikMigracji = await migrujPlikiBazyDoSzyfru({
        rootDirectory: ROOT_DIRECTORY,
        key: szyfrBazy.klucz(),
      });
      if (wynikMigracji.zaszyfrowane.length || wynikMigracji.zaszyfrowaneMigawki) {
        console.log(`Szyfr bazy: zaszyfrowano ${wynikMigracji.zaszyfrowane.length} plików i ${wynikMigracji.zaszyfrowaneMigawki} migawek kopii zapasowych.`);
      }
      for (const wpis of wynikMigracji.bledy) console.error("Szyfr bazy - migracja:", wpis);
    } catch (error) {
      console.error("Szyfr bazy: migracja nie powiodła się.", error?.message || error);
    }
  } else if (szyfrBazy.stan() === "nieodczytany") {
    const kontoKlucza = szyfrBazy.kontoKlucza();
    console.error(`Szyfr bazy: klucz czeka na przywrócenie kluczem ratunkowym (inny komputer lub konto Windows).${
      kontoKlucza ? ` Plik klucza zapisało konto: ${kontoKlucza}.` : ""
    }`);
  } else if (szyfrBazy.stan() === "niedostepny") {
    console.error("Szyfr bazy: ochrona danych Windows jest niedostępna - baza pozostaje niezaszyfrowana.");
  }
}
const routeStore = createPortableRouteStore({
  storageDirectory: join(FILES_DIRECTORY, "routetu"),
  defaultsDirectory: join(FILES_DIRECTORY, "llopfcklkccjjlikfqjj"),
});
await routeStore.seedDefaultRoutes().catch(() => {});


const portfolioImportState = createPortfolioImportState({
  storagePath: join(ROOT_DIRECTORY, "polisy-importy.json"),
});
const portfolioImportReviewStore = createPortfolioImportReviewStore({
  storagePath: join(ROOT_DIRECTORY, "polisy-importy-do-wyjasnienia.json"),
});
const portfolioCheckpointResetsInProgress = new Set();




const kontoStore = createKontoStore({
  storagePath: join(ROOT_DIRECTORY, "polisy-konto.json"),
  readExistingAccountId: async () => {
    const raw = await szyfrBazy.odczytajPlik(join(ROOT_DIRECTORY, "polisy-dane.json"));
    return JSON.parse(raw.toString("utf8"))?.accountId || "";
  },
});

const PORTFOLIO_INSURER_IDS = new Set([
  "allianz",
  "compensa",
  "generali",
  "hestia",
  "insly",
  "mtu",
  "pzu",
  "trasti",
  "warta",
  "wiener",
]);

function normalizePortfolioCheckpointScope(value) {
  return String(value || "")
    .normalize("NFKC")
    .trim()
    .toLocaleLowerCase("pl-PL")
    .slice(0, 200);
}





async function createPortfolioCheckpointKey(insurerId, {
  sourceAccount = "",
  portfolioId = "",
} = {}) {
  const insurer = String(insurerId || "").trim().toLowerCase();
  if (!PORTFOLIO_INSURER_IDS.has(insurer)) {
    throw createJobGuardError("JOB_CONFIGURATION_ERROR");
  }
  const normalizedPortfolioId = normalizePortfolioCheckpointScope(portfolioId);
  const snapshot = await kontoStore.getSnapshot().catch(() => null);
  const agencyId = normalizeAccountId(snapshot?.account?.id);
  const normalizedSourceAccount = normalizePortfolioCheckpointScope(sourceAccount);
  if (!agencyId && !normalizedSourceAccount && !normalizedPortfolioId) return insurer;
  const scopeDigest = createHash("sha256")
    .update(JSON.stringify([
      insurer,
      agencyId,
      normalizedSourceAccount,
      normalizedPortfolioId,
    ]))
    .digest("hex")
    .slice(0, 24);
  return `${insurer}:${scopeDigest}`;
}

async function initializePortfolioCheckpoint(job, insurerId, scope = {}) {
  if (portfolioCheckpointResetsInProgress.has(String(insurerId || "").toLowerCase())) {
    const error = new Error("Trwa bezpieczne zerowanie checkpointu tego towarzystwa.");
    error.code = "PORTFOLIO_CHECKPOINT_RESET_IN_PROGRESS";
    error.statusCode = 409;
    throw error;
  }
  const stateKey = await createPortfolioCheckpointKey(insurerId, scope);
  job.portfolioStateKey = stateKey;
  const sourceAccountRequired = scope.requireSourceAccountForIncremental === true;
  const sourceAccountKnown = Boolean(normalizePortfolioCheckpointScope(scope.sourceAccount));
  const reviewPendingBefore = job.pdfBacklogOnly === true
    ? 0
    : await portfolioImportReviewStore.getPendingCount(stateKey);
  const effectiveFullReimport = job.forceFullReimport === true
    || (sourceAccountRequired && !sourceAccountKnown)
    || reviewPendingBefore > 0;
  job.effectiveFullReimport = effectiveFullReimport;
  job.reviewPendingBefore = reviewPendingBefore;
  job.reviewPendingCount = reviewPendingBefore;
  const sinceDate = effectiveFullReimport
    ? ""
    : await portfolioImportState.getImportSinceDate(stateKey).catch(() => "");
  job.importSinceDate = sinceDate;
  return { stateKey, sinceDate };
}

const employeePackageImportTransactionStore = createEmployeePackageImportTransactionStore({
  storageDirectory: join(FILES_DIRECTORY, "tmp", "importy-pracownikow"),
  attachmentsRoot: join(ROOT_DIRECTORY, "Zalaczniki"),
});
const employeeAssignmentImportTransactionStore = createEmployeeAssignmentImportTransactionStore({
  storageDirectory: join(FILES_DIRECTORY, "tmp", "importy-przydzialow"),
  attachmentsRoot: join(ROOT_DIRECTORY, "Zalaczniki"),
});
const trainingDiagnosticsStore = createTrainingDiagnosticsStore({
  storageDirectory: join(FILES_DIRECTORY, "tmp", "diagnostyka-formularzy"),
});


const appVersion = await readFile(join(FILES_DIRECTORY, "wersja-aplikacji.json"), "utf8")
  .then((raw) => String(JSON.parse(raw)?.version || ""))
  .catch(() => "");
const diagnostykaStore = createDiagnostykaStore({
  storagePath: join(ROOT_DIRECTORY, "polisy-diagnostyka.json"),
  appVersion,
});






const licencjaStore = createLicencjaStore({
  storagePath: join(ROOT_DIRECTORY, "polisy-licencja.json"),
  vault: credentialVault,
});
const updateService = createUpdateService({
  rootDirectory: ROOT_DIRECTORY,
  updateBaseUrl: UPDATE_BASE_URL,
  licencja: licencjaStore,
  readAccountId: async () => (await kontoStore.getSnapshot())?.account?.id || "",
});








async function zdeponujKluczRatunkowyJesliTrzeba({ cisza = false } = {}) {
  if (!szyfrBazy.aktywny() || szyfrBazy.depozytAktualny()) return false;
  try {
    await updateService.wyslijKluczRatunkowy(szyfrBazy.kluczRatunkowyHex());
    await szyfrBazy.zapiszDepozyt();
    console.log("Szyfr bazy: klucz ratunkowy zdeponowany u producenta.");
    return true;
  } catch (error) {
    if (!cisza) console.error("Szyfr bazy: depozyt klucza ratunkowego odłożony.", error?.message || error);
    return false;
  }
}
void zdeponujKluczRatunkowyJesliTrzeba();



const licencjaProgramu = createLicencjaProgramu({
  store: licencjaStore,
  updateService,
  sciezkiZnacznikow: [
    join(ROOT_DIRECTORY, "polisy-dane.json"),
    join(ROOT_DIRECTORY, "polisy-licencja.json"),
    join(ROOT_DIRECTORY, "polisy-ustawienia.json"),
    join(ROOT_DIRECTORY, "polisy-diagnostyka.json"),
  ],
});




const answerStore = createAnswerStore({
  storagePath: join(ROOT_DIRECTORY, "polisy-odpowiedzi.json"),
  szyfr: {
    aktywny: () => szyfrBazy.aktywny(),
    czyZaszyfrowany: czyZaszyfrowanaBaza,
    zaszyfruj: (text) => szyfrBazy.zaszyfruj(text),
    odszyfruj: (buffer) => szyfrBazy.odszyfruj(buffer),
  },
});
await answerStore.init().catch(() => {});







const policyPdfReader = createPolicyPdfReader({
  attachmentsRoot: join(ROOT_DIRECTORY, "Zalaczniki"),
  filesDirectory: FILES_DIRECTORY,
});
function applyCommonHeaders(response) {
  response.setHeader("Cache-Control", "no-store");
  response.setHeader("X-Content-Type-Options", "nosniff");
  response.setHeader("Referrer-Policy", "no-referrer");
  response.setHeader("Cross-Origin-Resource-Policy", "same-origin");
  response.setHeader("X-Frame-Options", "DENY");
  response.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()");
  response.setHeader("Content-Security-Policy", [
    "default-src 'self'",
    "script-src 'self'",
    "style-src 'self' 'unsafe-inline'",
    "img-src 'self' data: blob: http: https:",
    "font-src 'self' data:",
    "connect-src 'self' http: https:",
    "media-src 'self' blob: http: https:",
    "frame-src https://www.youtube-nocookie.com",
    "worker-src 'self' blob:",
    "object-src 'self' blob:",
    "base-uri 'none'",
    "form-action 'self'",
    "frame-ancestors 'none'",
  ].join("; "));
}

function sendJson(response, statusCode, data) {
  if (response.writableEnded) return false;
  if (response.headersSent) {
    response.destroy();
    return false;
  }
  applyCommonHeaders(response);
  response.statusCode = statusCode;
  response.setHeader("Content-Type", "application/json; charset=utf-8");
  response.end(JSON.stringify(data));
  return true;
}

const SAFE_PORTFOLIO_GLOBAL_ERROR_CODES = new Set([
  "INSLY_PDF_MAP_INCOMPLETE",
  "INSLY_PDF_PHASE_FAILED",
]);

function getPublicJob(job) {
  return {
    id: job.id,
    insurer: job.insurer,
    insurerId: job.insurerId,
    kind: job.kind,
    status: job.status,
    title: job.title,
    detail: job.detail,
    premiums: job.premiums,
    policies: Array.isArray(job.policies) ? job.policies : [],
    records: Array.isArray(job.records) ? job.records : [],
    navigationLearned: job.navigationLearned,
    manualAvailable: job.manualAvailable === true,
    manualMode: job.manualMode === true,
    noNewPolicies: job.noNewPolicies === true,
    fullReimport: job.effectiveFullReimport === true || job.forceFullReimport === true,
    pdfBacklogOnly: job.pdfBacklogOnly === true,
    checkpointKey: /^[a-z0-9][a-z0-9:_-]{0,79}$/i.test(String(job.portfolioStateKey || ""))
      ? job.portfolioStateKey
      : null,
    cancelledByUser: job.cancelledByUser === true,
    pdfQueueRemaining: Number.isFinite(job.pdfQueueRemaining) ? job.pdfQueueRemaining : null,
    pdfQueuePolicyNumbers: normalizePortfolioPdfIdentityList(
      job.pdfQueuePolicyNumbers,
      job.insurerId,
      10_000,
    ),
    globalError: SAFE_PORTFOLIO_GLOBAL_ERROR_CODES.has(job.globalError)
      ? job.globalError
      : null,
    ambiguousCount: Number.isFinite(job.ambiguousCount)
      ? Math.max(0, Math.min(100000, Math.trunc(job.ambiguousCount)))
      : 0,
    mappingReport: getPublicPortfolioMappingSummary(job.mappingReport),
    reviewRequiredCount: Number.isFinite(job.reviewRequiredCount)
      ? Math.max(0, Math.min(100000, Math.trunc(job.reviewRequiredCount)))
      : 0,
    reviewPendingCount: Number.isFinite(job.reviewPendingCount)
      ? Math.max(0, Math.min(100000, Math.trunc(job.reviewPendingCount)))
      : 0,
    inputRequest: job.inputRequest || null,
    vehicleData: job.vehicleData || null,
    history: Array.isArray(job.history) ? job.history : [],
    createdAt: job.createdAt,
    updatedAt: job.updatedAt,
    consumedAt: Number.isFinite(job.consumedAt) ? job.consumedAt : null,
    pdfRetry: serializePortfolioPdfRetryStatus(job.pdfRetry),
  };
}

const PDF_RETRY_JOB_STATUSES = new Set(["completed", "consumed", "error"]);





function normalizePortfolioPdfIdentityList(values, insurer, limit) {
  const maximum = Number.isSafeInteger(limit) && limit > 0 ? limit : 10_000;
  const identitiesByKey = new Map();
  for (const value of Array.isArray(values) ? values.slice(0, maximum) : []) {
    try {
      const identity = createPortfolioPdfIdentity({
        insurer,
        policyNumber: value && typeof value === "object"
          ? value.policyNumber
          : value,
        validFrom: value && typeof value === "object" ? value.validFrom : "",
        validUntil: value && typeof value === "object" ? value.validUntil : "",
      });
      identitiesByKey.set(identity.key, {
        insurer: identity.insurer,
        policyNumber: identity.policyNumber,
        validFrom: identity.validFrom,
        validUntil: identity.validUntil,
      });
    } catch {
      
      
    }
  }
  return [...identitiesByKey.values()];
}

function preparePortfolioPdfJobDirectory(jobId) {
  return createPortfolioPdfJobDirectory({
    filesDirectory: FILES_DIRECTORY,
    jobId,
  });
}

function normalizeJobPdfRetryIdentities(job) {
  if (!Array.isArray(job?.pdfRetryIdentities)) return [];
  const identitiesByKey = new Map();
  for (const value of job.pdfRetryIdentities) {
    const identity = createPortfolioPdfIdentity(value);
    identitiesByKey.set(identity.key, identity);
  }
  return [...identitiesByKey.values()];
}

async function requestJobPdfManualRetry(job) {
  const identities = normalizeJobPdfRetryIdentities(job);
  if (identities.length === 0) {
    const error = new Error("Ten import nie ma dokumentów PDF do ponowienia.");
    error.statusCode = 409;
    throw error;
  }

  const resetResult = await portfolioPdfRetryStore.requestManualRetries(identities);
  if (!Number.isSafeInteger(resetResult?.reset) || resetResult.reset <= 0) {
    const error = new Error("Ten import nie ma aktywnej kwarantanny ani oczekującego ponowienia PDF.");
    error.statusCode = 409;
    throw error;
  }
  const previous = serializePortfolioPdfRetryStatus(job.pdfRetry) || {};
  const pdfRetry = {
    ...previous,
    backoff: 0,
    quarantined: 0,
    earliestNextRetryAt: null,
    batchComplete: false,
    circuitOpen: false,
    circuitCode: null,
    manualRetryAvailable: false,
  };
  updateJob(job, { pdfRetry });
  return pdfRetry;
}

const TERMINAL_JOB_STATUSES = new Set(["completed", "consumed", "error", "manual_required", "manual_ready"]);


const RUNNING_PORTFOLIO_JOB_STATUSES = new Set([
  "queued",
  "running",
  "action_required",
  "input_required",
]);
const SAFE_JOB_ERROR_IDENTIFIERS = new Set([
  "JOB_TIMEOUT",
  "JOB_CANCELLED",
  "QUEUE_BLOCKED",
  "SERVICE_SHUTTING_DOWN",
  "JOB_CONFIGURATION_ERROR",
  "CANCEL_TIMEOUT",
  "CANCEL_FAILED",
  "EACCES",
  "EPERM",
  "ESRCH",
  "ETIMEDOUT",
  "JOBEXECUTIONTIMEOUTERROR",
  "JOBQUEUEBLOCKEDERROR",
]);




const PORTFOLIO_EXTRA_ERROR_IDENTIFIERS = new Set([
  "MANUAL_INTERACTION_REQUIRED",
  "TRASTI_DETAIL_FETCH_FAILED",
  "INSLY_PDF_TOKEN_FAILED",
  "PORTFOLIO_MAPPING_INCOMPLETE",
  "PORTFOLIO_IMPORT_REVIEW_STORE_UNREADABLE",
  "PORTFOLIO_IMPORT_REVIEW_STORE_FULL",
  "PORTFOLIO_IMPORT_STATE_UNREADABLE",
  "PORTFOLIO_CHECKPOINT_RESET_IN_PROGRESS",
  "JOB_CANCELLED",
  "ABORT_ERR",
  "RESPONSE_ABORTED",
  "ECONNREFUSED",
  "ECONNRESET",
  "ENOTFOUND",
  "EAI_AGAIN",
]);



const NETWORK_ERROR_CODE_PATTERN = /net::(ERR_[A-Z][A-Z0-9_]{0,39})/;




function classifyUnknownPortfolioFailure(error) {
  for (const rawValue of [error?.code, error?.name]) {
    const candidate = String(rawValue || "")
      .toUpperCase()
      .replace(/[^A-Z0-9_-]/g, "_")
      .slice(0, 48);
    if (PORTFOLIO_EXTRA_ERROR_IDENTIFIERS.has(candidate)) return candidate;
  }
  
  
  if (String(error?.name || "") === "TimeoutError") return "NAV_TIMEOUT";
  const networkMatch = NETWORK_ERROR_CODE_PATTERN.exec(String(error?.message || ""));
  if (networkMatch) return networkMatch[1];
  const status = Number(error?.statusCode ?? error?.status);
  if (Number.isInteger(status) && status >= 100 && status <= 599) return `HTTP_${status}`;
  return "JOB_FAILED";
}




const PORTFOLIO_STAGE_PATTERNS = [
  ["reczne", /(okno przegl|kod sms|captcha|potwierd)/i],
  ["logowanie", /(logowani|zalogowano|otwieranie okna)/i],
  ["pdf", /pdf/i],
  ["szczegoly", /(szczeg|składek|skladek)/i],
  ["lista", /(pobieranie polis|listy polis|odczytywanie listy|sprawdzono)/i],
  ["porzadkowanie", /(porządkowanie|porzadkowanie)/i],
  ["start", /(uruchamianie|oczekiwanie)/i],
];

function describeJobFailureStage(job) {
  const history = Array.isArray(job?.history) ? job.history : [];
  for (let index = history.length - 1; index >= 0; index -= 1) {
    const entry = history[index];
    const text = `${entry?.title || ""} ${entry?.detail || ""}`;
    for (const [stage, pattern] of PORTFOLIO_STAGE_PATTERNS) {
      if (pattern.test(text)) return stage;
    }
  }
  return "";
}

function createJobGuardError(code) {
  const error = new Error("Zadanie automatyzacji nie może zostać uruchomione.");
  error.name = "JobGuardError";
  error.code = code;
  return error;
}

function safeJobErrorIdentifier(error) {
  for (const rawValue of [error?.code, error?.name]) {
    const candidate = String(rawValue || "")
      .toUpperCase()
      .replace(/[^A-Z0-9_-]/g, "_")
      .slice(0, 48);
    if (SAFE_JOB_ERROR_IDENTIFIERS.has(candidate)) return candidate;
  }
  return "JOB_FAILED";
}

function updateJob(job, changes) {
  
  
  if (job?.watchdogExpired === true) return false;
  Object.assign(job, changes, { updatedAt: Date.now() });
  
  
  if (changes && (changes.status || changes.title || changes.detail !== undefined)) {
    const entry = {
      at: Date.now(),
      status: String(job.status || ""),
      title: String(job.title || "").slice(0, 160),
      detail: String(job.detail || "").slice(0, 200),
    };
    const history = Array.isArray(job.history) ? job.history : [];
    const previous = history[history.length - 1];
    if (!previous || previous.status !== entry.status || previous.title !== entry.title || previous.detail !== entry.detail) {
      history.push(entry);
      job.history = history.slice(-80);
    }
  }
  return true;
}

function expireJobFromWatchdog(job) {
  
  
  if (typeof job?.pendingInput?.finish === "function") {
    job.pendingInput.finish(null);
  }
  updateJob(job, {
    status: "error",
    title: `${job.insurer}: przekroczono limit czasu`,
    detail: "Automatyzacja przekroczyła bezpieczny limit czasu i została zatrzymana.",
    premiums: [],
    policies: [],
    records: [],
    manualAvailable: false,
    inputRequest: null,
    watchdogExpired: true,
  });
  
  
}





function cancelJobByUser(job) {
  const statusBeforeCancellation = job?.status;
  if (typeof job?.pendingInput?.finish === "function") {
    job.pendingInput.finish(null);
  }
  updateJob(job, {
    status: "error",
    title: `${job.insurer}: zatrzymano na życzenie`,
    detail: "Zadanie zostało zatrzymane przez użytkownika.",
    premiums: [],
    policies: [],
    records: [],
    manualAvailable: false,
    inputRequest: null,
    watchdogExpired: true,
    cancelledByUser: true,
  });
  const automation = automationByInsurerId.get(job?.insurerId);
  const hasOtherLiveJobForInsurer = [...jobs.values()].some((candidate) => (
    candidate !== job
    && candidate.insurerId === job?.insurerId
    && ["running", "action_required", "input_required", "manual_required", "manual_ready"].includes(candidate.status)
  ));
  
  
  
  const shouldCloseAutomation = statusBeforeCancellation !== "queued"
    && !hasOtherLiveJobForInsurer;
  let closeAttempt = Promise.resolve({ status: "not_started" });
  if (shouldCloseAutomation && automation && typeof automation.close === "function") {
    
    
    
    let closeTimer = null;
    closeAttempt = Promise.race([
      Promise.resolve()
        .then(() => automation.close())
        .then(() => ({ status: "completed" }))
        .catch((error) => {
          console.error(`Automatyzacja ${job?.insurerId || "unknown"}: ${safeJobErrorIdentifier(error)}.`);
          return { status: "rejected" };
        }),
      new Promise((resolveTimeout) => {
        closeTimer = setTimeout(() => resolveTimeout({ status: "timeout" }), 15_000);
        closeTimer?.unref?.();
      }),
    ]).finally(() => {
      if (closeTimer !== null) clearTimeout(closeTimer);
    });
  }
  job.importTurnReleaseBarrier = closeAttempt;
  
  
  if (shouldCloseAutomation) {
    void closeAttempt.then((closeResult) => {
      if (closeResult?.status !== "timeout" && closeResult?.status !== "rejected") return;
      const reason = closeResult.status === "timeout" ? "CANCEL_TIMEOUT" : "CANCEL_FAILED";
      automationQueueByInsurerId.get(job?.insurerId)?.block?.(reason);
      console.error(`Automatyzacja ${job?.insurerId || "unknown"}: kolejka zablokowana (${reason}).`);
    });
  }
  
  
  let releasePromise = Promise.resolve();
  if (typeof job?.releaseImportTurn === "function") {
    releasePromise = Promise.resolve(job.releaseImportTurn());
  }
  releasePromise.catch(() => {});
  if (typeof job?.releaseQuoteTurn === "function") {
    Promise.resolve(job.releaseQuoteTurn()).catch(() => {});
  }
  
  
  if (typeof job?.kind === "string" && job.kind.startsWith("portfolio")) {
    recordPortfolioImportFailure(
      job.portfolioStateKey || job.insurerId || "unknown",
      job,
      createJobGuardError("JOB_CANCELLED"),
    );
  }
  
  
  job.cancellationPromise = closeAttempt.then(() => undefined);
  return job.cancellationPromise;
}

function registerQuoteJob(job, enqueue) {
  jobs.set(job.id, job);
  
  
  if (job.clientBatchId && isQuoteBatchCancelled(job.clientBatchId)) {
    void cancelJobByUser(job);
    return false;
  }
  enqueue();
  return true;
}

async function cancelQuoteBatchById(batchId) {
  const normalizedBatchId = markQuoteBatchCancelled(batchId);
  if (!normalizedBatchId) throw new Error("Nieprawidłowy identyfikator paczki kalkulacji.");
  const batchJobs = [...jobs.values()].filter((job) => (
    job.kind === "quote" && job.clientBatchId === normalizedBatchId
  ));
  await Promise.all(batchJobs.map(async (job) => {
    if (job.cancelledByUser === true) {
      await job.cancellationPromise?.catch(() => {});
      return;
    }
    const canCancel = job.watchdogExpired !== true
      && (!TERMINAL_JOB_STATUSES.has(job.status)
        || job.status === "manual_required"
        || job.status === "manual_ready");
    if (canCancel) await cancelJobByUser(job);
  }));
  return batchJobs;
}





const TECHNICAL_ERROR_MESSAGE_PATTERN = new RegExp([
  "Runtime\\.",
  "Protocol error",
  "Protocol Timeout",
  "Target closed",
  "Session closed",
  "Connection closed",
  "net::",
  "waiting for selector",
  "Navigation timeout",
  "Execution context",
  "WebSocket",
  "ECONN",
  "ETIMEDOUT",
  "ERR_",
].join("|"), "i");

function friendlyAutomationErrorDetail(error, fallback = "Sprawdź otwarte okno Google Chrome.") {
  const message = String(error?.message || "").replace(/\s+/g, " ").trim();
  if (!message) return fallback;
  if (TECHNICAL_ERROR_MESSAGE_PATTERN.test(message)) {
    return "Przeglądarka automatyzacji nie odpowiedziała na czas. Spróbuj ponownie za chwilę.";
  }
  return message.slice(0, 500);
}

function handleAutomationJobRejection(error, context) {
  const insurerId = automationByInsurerId.has(context?.insurerId)
    ? context.insurerId
    : "unknown";
  const code = safeJobErrorIdentifier(error);
  const job = context?.job;
  
  
  
  if (typeof job?.kind === "string" && job.kind.startsWith("portfolio")) {
    recordPortfolioImportFailure(job.portfolioStateKey || job.insurerId || insurerId, job, error);
  }
  if (job && job.watchdogExpired !== true && !TERMINAL_JOB_STATUSES.has(job.status)) {
    updateJob(job, {
      status: "error",
      title: `${job.insurer}: zadanie zostało przerwane`,
      detail: code === "QUEUE_BLOCKED"
        ? "Kolejka tego towarzystwa jest zablokowana po nieudanym zamknięciu przeglądarki. Uruchom ponownie Bazę Polis."
        : code === "SERVICE_SHUTTING_DOWN"
          ? "Aplikacja jest zamykana. Uruchom ją ponownie, aby wykonać zadanie."
          : "Nie udało się bezpiecznie wykonać zadania automatyzacji.",
      manualAvailable: false,
      inputRequest: null,
    });
  }
  
  console.error(`Automatyzacja ${insurerId}: ${code}.`);
}

function runGuardedAutomationJob(job, run) {
  if (shuttingDown) throw createJobGuardError("SERVICE_SHUTTING_DOWN");
  
  
  
  if (job?.watchdogExpired === true || TERMINAL_JOB_STATUSES.has(job?.status)) {
    throw createJobGuardError("JOB_CANCELLED");
  }
  const automation = automationByInsurerId.get(job?.insurerId);
  if (!automation || typeof automation.close !== "function") {
    throw createJobGuardError("JOB_CONFIGURATION_ERROR");
  }
  return runWithDeadline({
    timeoutMs: getJobTimeoutMs(job?.kind),
    run,
    onTimeout: () => expireJobFromWatchdog(job),
    cancel: () => automation.close(),
  });
}

function enqueueAutomationJob(queue, job, run, { waitForPortfolioTurn = false, quoteTurnExempt = false } = {}) {
  const context = {
    job,
    insurerId: automationByInsurerId.has(job?.insurerId) ? job.insurerId : "unknown",
  };
  if (shuttingDown) {
    const error = createJobGuardError("SERVICE_SHUTTING_DOWN");
    handleAutomationJobRejection(error, context);
    return Promise.resolve({ ok: false, error });
  }
  const admission = waitForPortfolioTurn
    ? reservePortfolioImportTurn(job)
    : quoteTurnExempt
      ? null
      : reserveQuoteTurn(job);
  const queued = queue.enqueue(
    () => (
      waitForPortfolioTurn
        ? runWithPortfolioImportTurn(
          job,
          () => runGuardedAutomationJob(job, run),
          admission,
        )
        : quoteTurnExempt
          ? runGuardedAutomationJob(job, run)
          : runWithQuoteTurn(
            job,
            () => runGuardedAutomationJob(job, run),
            admission,
          )
    ),
    context,
  );
  
  
  if (admission) void queued.then(() => admission.release());
  return queued;
}

function validatePortfolioMappingReport(job, outcome) {
  const report = outcome?.mappingReport;
  if (job?.pdfBacklogOnly === true) {
    if (
      !report
      || report.coverage !== PORTFOLIO_MAPPING_PDF_BACKLOG_ONLY_COVERAGE
      || report.complete !== false
      || report.sourceCount !== 0
      || report.mappedCount !== 0
      || report.filteredCount !== 0
      || report.duplicateCount !== 0
      || report.rejectedCount !== 0
      || report.accountedCount !== 0
      || report.unexplainedCount !== 0
      || report.overcount !== 0
      || !Array.isArray(report.filters)
      || report.filters.length !== 0
      || !Array.isArray(report.rejections)
      || report.rejections.length !== 0
    ) {
      const error = new Error("Nie udało się potwierdzić zakresu pobierania zaległych PDF-ów.");
      error.code = "PORTFOLIO_MAPPING_INCOMPLETE";
      throw error;
    }
    return report;
  }
  return assertPortfolioMappingComplete(report);
}

function validatePortfolioEmission(job, {
  mappingReport,
  policies,
  outcome,
  sinceDate,
}) {
  const expectedCoverage = job?.pdfBacklogOnly === true
    ? PORTFOLIO_EMISSION_PDF_BACKLOG_ONLY_COVERAGE
    : String(sinceDate || "")
      ? PORTFOLIO_EMISSION_INCREMENTAL_COVERAGE
      : PORTFOLIO_EMISSION_FULL_COVERAGE;
  const emissionReport = assertPortfolioEmissionReport(outcome?.emissionReport, {
    expectedCoverage,
  });
  const emittedCount = Array.isArray(policies) ? policies.length : -1;
  const hasLegacyFreshCount = Object.prototype.hasOwnProperty.call(outcome || {}, "freshCount");
  const invalid = emittedCount < 0
    || emissionReport.mappedCount !== mappingReport.mappedCount
    || emissionReport.emittedCount !== emittedCount
    || (hasLegacyFreshCount && (
      !Number.isSafeInteger(outcome.freshCount)
      || outcome.freshCount < 0
      || outcome.freshCount !== emissionReport.freshCount
    ))
    || (job?.pdfBacklogOnly === true && (
      emissionReport.freshCount !== 0
      || emissionReport.beforeCheckpointCount !== 0
    ));
  if (invalid) {
    const error = new Error("Nie udało się potwierdzić kompletności rekordów przekazanych do zapisu.");
    error.code = "PORTFOLIO_MAPPING_INCOMPLETE";
    throw error;
  }
  return emissionReport;
}

function createSyntheticPortfolioReviewHash(stateKey, code, ordinal) {
  return createHash("sha256")
    .update([
      "portfolio-review",
      String(stateKey || ""),
      String(code || ""),
      String(ordinal),
    ].join("\0"), "utf8")
    .digest("hex");
}

function getMappingReviewIssues(stateKey, mappingReport) {
  const issues = [];
  for (const rejection of Array.isArray(mappingReport?.rejections)
    ? mappingReport.rejections
    : []) {
    const code = String(rejection?.code || "").trim().toUpperCase();
    const count = Number.isSafeInteger(rejection?.count)
      ? Math.max(0, rejection.count)
      : 0;
    const hashes = Array.isArray(rejection?.identityHashes)
      ? rejection.identityHashes
      : [];
    for (const identityHash of hashes) {
      if (issues.length >= 10_000) return issues;
      issues.push({ identityHash, code });
    }
    
    
    
    if (hashes.length < count && issues.length < 10_000) {
      issues.push({
        identityHash: createSyntheticPortfolioReviewHash(stateKey, code, 0),
        code,
      });
    }
  }
  return issues;
}

function getPublicPortfolioMappingSummary(report) {
  if (!report || typeof report !== "object") return null;
  return {
    sourceCount: report.sourceCount,
    mappedCount: report.mappedCount,
    filteredCount: report.filteredCount,
    duplicateCount: report.duplicateCount,
    rejectedCount: report.rejectedCount,
    unexplainedCount: report.unexplainedCount,
    coverage: report.coverage,
    complete: report.complete === true,
    filters: (Array.isArray(report.filters) ? report.filters : []).map(({ code, count }) => ({
      code,
      count,
    })),
    rejections: (Array.isArray(report.rejections) ? report.rejections : []).map(({
      code,
      count,
    }) => ({
      code,
      count,
    })),
  };
}





async function completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome = null, insurerLabel }) {
  const mappingReport = validatePortfolioMappingReport(job, outcome);
  const emissionReport = validatePortfolioEmission(job, {
    mappingReport,
    policies,
    outcome,
    sinceDate,
  });
  const freshCount = emissionReport.freshCount;
  const mappingReviewIssues = getMappingReviewIssues(stateKey, mappingReport);
  const pdfSaved = Number.isFinite(outcome?.pdfSaved) ? outcome.pdfSaved : null;
  const pdfRemaining = Number.isFinite(outcome?.pdfRemaining) ? outcome.pdfRemaining : null;
  const rawGlobalError = typeof outcome?.globalError === "string"
    ? outcome.globalError.trim()
    : "";
  const globalError = !rawGlobalError
    ? null
    : SAFE_PORTFOLIO_GLOBAL_ERROR_CODES.has(rawGlobalError)
      ? rawGlobalError
      : "INSLY_PDF_PHASE_FAILED";
  const ambiguousCount = Number.isFinite(outcome?.ambiguousCount)
    ? Math.max(0, Math.min(100000, Math.trunc(outcome.ambiguousCount)))
    : 0;
  const serverReviewIssues = [...mappingReviewIssues];
  if (ambiguousCount > 0) {
    serverReviewIssues.push({
      identityHash: createSyntheticPortfolioReviewHash(
        stateKey,
        "AMBIGUOUS_PDF_MAPPING",
        0,
      ),
      code: "AMBIGUOUS_PDF_MAPPING",
    });
  }
  job.mappingReport = mappingReport;
  job.emissionReport = emissionReport;
  job.serverReviewIssues = serverReviewIssues;
  job.reviewRequiredCount = mappingReport.rejectedCount + ambiguousCount;
  
  
  const pdfQueuePolicyNumbers = normalizePortfolioPdfIdentityList(
    outcome?.pdfQueuePolicyNumbers,
    job.insurerId,
    10_000,
  );
  const normalizedStateKey = String(stateKey || "");
  const isInslyImport = job.insurerId === "insly"
    || normalizedStateKey === "insly"
    || normalizedStateKey.startsWith("insly:");
  const hasInslyPdfBlocker = isInslyImport
    && globalError !== null;
  diagnostykaStore.zapiszBiegImportu(stateKey, {
    wynik: hasInslyPdfBlocker ? "blad" : (policies.length === 0 ? "brak-nowych" : "sukces"),
    trybPrzyrostowy: Boolean(sinceDate),
    dataOd: sinceDate || "",
    nowychPolis: freshCount,
    zwroconoWpisow: policies.length,
    pobieraniePdf: job.downloadPdfs === true,
    ...(pdfSaved === null ? {} : { pdfPobrano: pdfSaved }),
    ...(pdfRemaining === null ? {} : { pdfWKolejce: pdfRemaining }),
    ...(globalError === null ? {} : { kodBleduPdf: globalError }),
    ...(ambiguousCount > 0 ? { pdfNiejednoznaczne: ambiguousCount } : {}),
    mapowanieZrodlo: mappingReport.sourceCount,
    mapowaniePoprawne: mappingReport.mappedCount,
    mapowanieOdrzucone: mappingReport.rejectedCount,
    mapowanieNiewyjasnione: mappingReport.unexplainedCount,
    czasSekund: Math.round((Date.now() - (job.createdAt || Date.now())) / 1000),
  });
  if (hasInslyPdfBlocker) {
    updateJob(job, {
      status: "error",
      title: "Import polis z Superpolisy wymaga ponowienia",
      detail: "Nie udało się kompletnie i jednoznacznie pobrać dokumentów. Uruchom import ponownie albo wyłącz pobieranie PDF.",
      policies: [],
      noNewPolicies: false,
      pdfQueueRemaining: pdfRemaining,
      globalError,
      ambiguousCount,
      manualAvailable: false,
      consumedAt: null,
    });
    return;
  }
  if (policies.length === 0) {
    const reviewDetail = job.reviewRequiredCount > 0
      ? `Do wyjaśnienia zapisano ${job.reviewRequiredCount} rekordów.`
      : "";
    updateJob(job, {
      status: "completed",
      title: job.pdfBacklogOnly === true
        ? "Pobieranie zaległych PDF-ów zatrzymane"
        : "Brak nowych polis do pobrania",
      detail: [
        pdfRemaining > 0
          ? `W kolejce do pobrania zostało ${pdfRemaining} plików PDF starszych polis.`
          : "",
        reviewDetail,
      ].filter(Boolean).join(" "),
      policies: [],
      noNewPolicies: true,
      pdfQueueRemaining: pdfRemaining,
      pdfQueuePolicyNumbers,
      globalError,
      ambiguousCount,
      manualAvailable: false,
      portfolioStateKey: stateKey,
      portfolioCompletedAt: Date.now(),
      consumedAt: null,
    });
    return;
  }
  const detailParts = [];
  if (sinceDate) detailParts.push(freshCount > 0 ? `Nowych polis: ${freshCount}.` : "Brak nowych polis.");
  else detailParts.push(`Pobrano ${policies.length} polis.`);
  if (pdfSaved > 0) detailParts.push(`Pobrano ${pdfSaved} plików PDF.`);
  if (pdfRemaining > 0) detailParts.push(`W kolejce zostało ${pdfRemaining} plików PDF.`);
  if (job.reviewRequiredCount > 0) {
    detailParts.push(`Do wyjaśnienia zapisano ${job.reviewRequiredCount} rekordów.`);
  }
  updateJob(job, {
    status: "completed",
    title: `Import polis z ${insurerLabel} zakończony`,
    detail: detailParts.join(" "),
    policies,
    pdfQueueRemaining: pdfRemaining,
    pdfQueuePolicyNumbers,
    globalError,
    ambiguousCount,
    manualAvailable: false,
    portfolioStateKey: stateKey,
    portfolioCompletedAt: Date.now(),
    consumedAt: null,
  });
}

const PORTFOLIO_ACK_REVIEW_CODES = new Set([
  "AMBIGUOUS_MERGE",
  "MERGE_REJECTED",
  "PDF_PERIOD_MISMATCH",
]);

function normalizePortfolioAckReviewIssues(job, payload) {
  const rawIssues = payload?.reviewIssues;
  if (rawIssues === undefined) return [];
  if (!Array.isArray(rawIssues) || rawIssues.length > 10_000) {
    const error = new Error("Nieprawidłowy raport rekordów wymagających wyjaśnienia.");
    error.statusCode = 400;
    throw error;
  }
  const issuesByKey = new Map();
  for (const rawIssue of rawIssues) {
    const code = String(rawIssue?.code || "").trim().toUpperCase();
    if (!PORTFOLIO_ACK_REVIEW_CODES.has(code)) {
      const error = new Error("Nieprawidłowy kod rekordu wymagającego wyjaśnienia.");
      error.statusCode = 400;
      throw error;
    }
    let identityHash;
    try {
      const identityInsurer = job?.insurerId === "insly"
        ? normalizePortfolioPdfInsurer(rawIssue?.insurer)
        : job?.insurerId;
      identityHash = createPortfolioIssueIdentityHash({
        insurer: identityInsurer,
        sourceId: rawIssue?.sourceId ?? rawIssue?.policyId ?? "",
        policyNumber: rawIssue?.policyNumber,
        validFrom: rawIssue?.validFrom,
        validUntil: rawIssue?.validUntil,
      });
    } catch {
      const error = new Error("Rekord wymagający wyjaśnienia nie ma bezpiecznej tożsamości.");
      error.statusCode = 400;
      throw error;
    }
    issuesByKey.set(`${identityHash}:${code}`, { identityHash, code });
  }
  return [...issuesByKey.values()];
}

function mergePortfolioReviewIssues(...groups) {
  const issuesByKey = new Map();
  for (const group of groups) {
    for (const issue of Array.isArray(group) ? group : []) {
      issuesByKey.set(`${issue.identityHash}:${issue.code}`, issue);
    }
  }
  return [...issuesByKey.values()].slice(0, 10_000);
}

function createPortfolioAckReviewDigest(issues) {
  const canonical = (Array.isArray(issues) ? issues : [])
    .map((issue) => `${issue.identityHash}:${issue.code}`)
    .sort()
    .join("\n");
  return createHash("sha256").update(canonical, "utf8").digest("hex");
}



async function consumeCompletedPortfolioJob(job, payload = {}) {
  if (job?.kind !== "portfolio") {
    const error = new Error("Ten job nie jest importem portfela.");
    error.statusCode = 409;
    throw error;
  }
  if (job.status !== "completed" && job.status !== "consumed") {
    const error = new Error("Import portfela nie jest jeszcze gotowy do zatwierdzenia.");
    error.statusCode = 409;
    throw error;
  }
  
  
  
  if (job.status === "completed" && typeof job.globalError === "string") {
    const error = new Error("Import zawiera niekompletną fazę dokumentów i nie może zostać zatwierdzony.");
    error.statusCode = 409;
    error.code = "PORTFOLIO_IMPORT_INCOMPLETE";
    throw error;
  }
  if (job.status === "completed" && !job.portfolioStateKey) {
    const error = new Error("Import portfela nie ma klucza checkpointu.");
    error.statusCode = 500;
    throw error;
  }
  const frontendReviewIssues = normalizePortfolioAckReviewIssues(job, payload);
  const reviewDigest = createPortfolioAckReviewDigest(frontendReviewIssues);
  if (job.ackReviewDigest && job.ackReviewDigest !== reviewDigest) {
    const error = new Error("Ponowione potwierdzenie importu ma inną listę rekordów do wyjaśnienia.");
    error.statusCode = 409;
    error.code = "PORTFOLIO_ACK_PAYLOAD_CONFLICT";
    throw error;
  }
  if (!job.ackReviewDigest) job.ackReviewDigest = reviewDigest;
  if (job.status === "consumed") return;
  if (!job.consumingPromise) {
    job.consumingPromise = (async () => {
      if (job.reviewIssuesRecorded !== true) {
        const reviewIssues = mergePortfolioReviewIssues(
          job.serverReviewIssues,
          frontendReviewIssues,
        );
        const pendingCount = await portfolioImportReviewStore.recordRunIssues(
          job.portfolioStateKey,
          reviewIssues,
          {
            fullCoverage: job.pdfBacklogOnly !== true
              && !String(job.importSinceDate || ""),
          },
        );
        job.reviewIssuesRecorded = true;
        job.reviewRequiredCount = reviewIssues.length;
        job.reviewPendingCount = pendingCount;
      }
      
      
      if (job.pdfBacklogOnly !== true) {
        await portfolioImportState.markImportCompleted(job.portfolioStateKey);
      }
      updateJob(job, {
        status: "consumed",
        title: `${job.title} - zapis potwierdzony`,
        consumedAt: Date.now(),
      });
      if (job.pdfDirectory) {
        await cleanupPortfolioPdfJobDirectory({
          filesDirectory: FILES_DIRECTORY,
          jobId: job.id,
          jobDirectory: job.pdfDirectory,
        }).catch(() => {
          
          
          console.error("Katalog tymczasowy PDF joba nie został bezpiecznie usunięty.");
        });
      }
    })();
  }
  try {
    await job.consumingPromise;
  } finally {
    delete job.consumingPromise;
  }
}




function recordPortfolioImportFailure(stateKey, job, error) {
  if (job && typeof job === "object") {
    if (job.failureRecorded === true) return;
    job.failureRecorded = true;
  }
  const allowlistedCode = safeJobErrorIdentifier(error);
  const failureCode = job?.cancelledByUser === true
    ? "JOB_CANCELLED"
    : job?.watchdogExpired === true
      ? "JOB_TIMEOUT"
      : allowlistedCode !== "JOB_FAILED"
        ? allowlistedCode
        : classifyUnknownPortfolioFailure(error);
  
  
  const failureStage = describeJobFailureStage(job);
  diagnostykaStore.zapiszBiegImportu(stateKey, {
    wynik: "blad",
    blad: failureCode,
    ...(failureStage ? { etap: failureStage } : {}),
    czasSekund: Math.round((Date.now() - (job.createdAt || Date.now())) / 1000),
  });
  
  
  
  
  
  const insurerPrefix = String(stateKey || job?.insurerId || "unknown").split(":")[0];
  console.error(`Import ${insurerPrefix}: ${failureCode}${failureStage ? ` (etap: ${failureStage})` : ""}.`);
}

function sanitizeInputRequestFields(fields) {
  return (Array.isArray(fields) ? fields : []).slice(0, 25).map((field) => ({
    id: String(field?.id || "").slice(0, 30),
    kind: ["text", "number", "date", "datetime", "month", "select", "checkbox", "radio", "combobox"].includes(field?.kind) ? field.kind : "text",
    label: String(field?.label || "").slice(0, 160),
    currentValue: String(field?.currentValue || "").slice(0, 120),
    placeholder: String(field?.placeholder || "").slice(0, 120),
    formatHint: String(field?.formatHint || "").slice(0, 120),
    required: field?.required === true,
    invalid: field?.invalid === true,
    options: (Array.isArray(field?.options) ? field.options : []).slice(0, 60).map((option) => ({
      value: String(option?.value || "").slice(0, 120),
      text: String(option?.text || "").slice(0, 120),
    })),
  })).filter((field) => field.id && field.label);
}



function sanitizeInslyPdfPolicyKeys(values, limit) {
  const normalized = [];
  const seen = new Set();
  for (const value of Array.isArray(values) ? values.slice(0, limit) : []) {
    const key = normalizeInslyPdfPolicyKey(value);
    if (!key || seen.has(key)) continue;
    seen.add(key);
    normalized.push(key);
  }
  return normalized;
}

const INPUT_ANSWER_TIMEOUT_MS = 30 * 60 * 1000;





function findOptionForStoredValue(field, storedValue) {
  const normalizedStoredValue = normalizeAnswerLabel(storedValue);
  if (!normalizedStoredValue) return null;
  for (const option of field.options) {
    const optionText = normalizeAnswerLabel(option?.text);
    if (!optionText) continue;
    if (optionText === normalizedStoredValue
      || (optionText.length >= 3 && optionText.includes(normalizedStoredValue))
      || (normalizedStoredValue.length >= 3 && normalizedStoredValue.includes(optionText) && optionText.length >= 3)) {
      return "";
    }
  }
  const trimmedValue = String(storedValue).trim();
  const isoDate = trimmedValue.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
  const polishDate = trimmedValue.match(/^(\d{1,2})[.-](\d{1,2})[.-](\d{4})$/);
  const year = isoDate ? isoDate[1] : polishDate ? polishDate[3] : "";
  if (year) {
    const yearOption = field.options.find((option) => String(option?.text || "").trim() === year);
    if (yearOption) return String(yearOption.text).trim();
  }
  const numericValue = Number(trimmedValue.replace(/\s/g, "").replace(",", "."));
  if (Number.isFinite(numericValue) && numericValue > 0) {
    for (const option of field.options) {
      const rangeMatch = String(option?.text || "").match(/(\d[\d\s]*)\s*-\s*(\d[\d\s]*)/);
      if (!rangeMatch) continue;
      const low = Number(rangeMatch[1].replace(/\s/g, ""));
      const high = Number(rangeMatch[2].replace(/\s/g, ""));
      if (Number.isFinite(low) && Number.isFinite(high) && low <= numericValue && numericValue <= high) {
        return String(option.text).trim();
      }
    }
  }
  return null;
}








function createPortfolioInputRequester(job) {
  return (request) => {
    if (job.watchdogExpired === true) return Promise.resolve(null);
    const fields = sanitizeInputRequestFields(request?.fields);
    if (fields.length === 0) return Promise.resolve(null);
    return new Promise((resolve) => {
      const requestId = randomUUID();
      const finish = (answers) => {
        if (job.pendingInput?.id !== requestId) return;
        globalThis.clearTimeout(job.pendingInput.timer);
        job.pendingInput = null;
        if (answers) {
          updateJob(job, {
            status: "running",
            title: `${job.insurer}: kod przyjęty, wracam do importu…`,
            detail: "",
            inputRequest: null,
          });
          resolve(answers);
          return;
        }
        updateJob(job, { inputRequest: null });
        resolve(null);
      };
      const timer = globalThis.setTimeout(() => finish(null), INPUT_ANSWER_TIMEOUT_MS);
      job.pendingInput = { id: requestId, finish, timer };
      updateJob(job, {
        status: "input_required",
        title: `${job.insurer}: przepisz kod z telefonu`,
        detail: request?.title
          ? `${String(request.title).slice(0, 120)}. Wpisz kod w oknie importu - nie musisz nigdzie klikać w przeglądarce.`
          : "Portal poprosił o kod potwierdzający. Wpisz go w oknie importu.",
        inputRequest: {
          id: requestId,
          title: String(request?.title || "").slice(0, 160),
          round: Math.max(1, Math.trunc(Number(request?.round)) || 1),
          fields,
        },
      });
    });
  };
}

function rememberJobVehicleDataFromAnswers(job, fields, values) {
  const discoveredData = extractVehicleDataFromFormAnswers({
    registration: job.request?.registration,
    fields,
    values,
  });
  if (!discoveredData) return false;
  job.vehicleData = mergeVehicleDataWithSource(
    job.vehicleData,
    discoveredData,
    "calculator-input",
  );
  return true;
}

function createJobInputRequester(job) {
  
  
  const autoAnsweredFieldKeys = new Set();
  return (request) => {
    if (job.watchdogExpired === true) return Promise.resolve(null);
    return new Promise((resolve) => {
    const rawFields = Array.isArray(request?.fields) ? request.fields : [];
    const registration = job.request?.registration || "";
    const pesel = job.request?.pesel || "";
    
    
    
    
    const labelCounts = new Map();
    for (const field of rawFields) {
      const normalizedLabel = normalizeAnswerLabel(field?.label);
      if (normalizedLabel) labelCounts.set(normalizedLabel, (labelCounts.get(normalizedLabel) || 0) + 1);
    }
    const autoValues = {};
    const remainingFields = [];
    for (const field of rawFields) {
      const fieldKey = `${field?.frameHint || ""}|${field?.selector || ""}|${field?.label || field?.id || ""}`;
      const normalizedLabel = normalizeAnswerLabel(field?.label);
      const uniqueLabel = Boolean(normalizedLabel) && labelCounts.get(normalizedLabel) === 1;
      let storedAnswer = null;
      if (field?.invalid !== true && uniqueLabel && !autoAnsweredFieldKeys.has(fieldKey)) {
        storedAnswer = answerStore.findAnswerForField({ registration, pesel, field });
      }
      
      
      
      if (!storedAnswer && field?.invalid !== true && uniqueLabel && !autoAnsweredFieldKeys.has(fieldKey)
        && /prawa jazdy/.test(normalizedLabel) && /(^| )rok( |$)/.test(normalizedLabel)) {
        const dateAnswer = answerStore.findAnswerForField({
          registration,
          pesel,
          field: { label: "Data uzyskania prawa jazdy", kind: "text" },
        });
        const yearMatch = String(dateAnswer?.value || "").match(/(19|20)\d{2}/);
        if (yearMatch) storedAnswer = { kind: "text", value: yearMatch[0], checked: false };
      }
      
      
      
      
      if (storedAnswer && Array.isArray(field?.options) && field.options.length > 0) {
        const matchedOptionText = findOptionForStoredValue(field, storedAnswer.value);
        if (matchedOptionText === null) storedAnswer = null;
        else if (matchedOptionText !== "") storedAnswer = { ...storedAnswer, value: matchedOptionText };
      }
      if (storedAnswer && field?.id) {
        autoAnsweredFieldKeys.add(fieldKey);
        autoValues[field.id] = storedAnswer.kind === "checkbox"
          ? { value: storedAnswer.value, checked: storedAnswer.checked }
          : storedAnswer.value;
      } else {
        remainingFields.push(field);
      }
    }
    const autoAnsweredCount = Object.keys(autoValues).length;
    if (rawFields.length > 0 && remainingFields.length === 0) {
      rememberJobVehicleDataFromAnswers(job, rawFields, autoValues);
      updateJob(job, {
        status: "running",
        title: `Uzupełnianie zapamiętanych odpowiedzi w ${job.insurer}…`,
        detail: "",
      });
      resolve(autoValues);
      return;
    }
    const fields = sanitizeInputRequestFields(remainingFields);
    if (fields.length === 0) {
      resolve(autoAnsweredCount > 0 ? autoValues : null);
      return;
    }
    const requestId = randomUUID();
    const finish = (answers) => {
      if (job.pendingInput?.id !== requestId) return;
      globalThis.clearTimeout(job.pendingInput.timer);
      job.pendingInput = null;
      if (answers) {
        
        
        try {
          answerStore.recordAnswers({
            registration,
            pesel,
            insurerId: job.insurerId,
            fields: remainingFields,
            values: answers,
          });
        } catch (error) {
          console.error("Magazyn odpowiedzi: nie udało się zapisać odpowiedzi.", error?.message || error);
        }
        rememberJobVehicleDataFromAnswers(job, rawFields, { ...autoValues, ...answers });
        updateJob(job, {
          status: "running",
          title: `Uzupełnianie danych w ${job.insurer}…`,
          detail: "",
          inputRequest: null,
        });
        resolve({ ...autoValues, ...answers });
        return;
      }
      updateJob(job, { inputRequest: null });
      resolve(null);
    };
    const timer = globalThis.setTimeout(() => finish(null), INPUT_ANSWER_TIMEOUT_MS);
    job.pendingInput = { id: requestId, finish, timer };
    updateJob(job, {
      status: "input_required",
      title: `${job.insurer}: uzupełnij brakujące pola`,
      detail: request?.title
        ? `Kalkulator zatrzymał się na ekranie „${String(request.title).slice(0, 120)}”. Uzupełnij pola w Bazie i kliknij „Wyślij i kontynuuj”.`
        : "Kalkulator potrzebuje dodatkowych danych. Uzupełnij pola w Bazie i kliknij „Wyślij i kontynuuj”.",
      inputRequest: {
        id: requestId,
        title: String(request?.title || "").slice(0, 160),
        round: Math.max(1, Math.trunc(Number(request?.round)) || 1),
        fields,
      },
    });
    });
  };
}

const QUOTE_VEHICLE_INFO_FIELDS = Object.freeze([
  "clientName",
  "clientFirstName",
  "clientLastName",
  "clientMaidenName",
  "clientAddress",
  "clientPostalCode",
  "clientPhone",
  "clientEmail",
  "identityNumber",
  "registration",
  "vehicleMake",
  "vehicleModel",
  "vehicleType",
  "vin",
  "firstRegistrationDate",
  "productionYear",
  "fuelType",
  "seats",
  "grossWeight",
  "engineCapacity",
  "enginePower",
  "mileage",
  "driverLicenseDate",
]);

function sanitizeQuoteVehicleInfo(payload) {
  if (!payload || typeof payload !== "object") return null;
  const vehicleInfo = {};
  let hasAnyValue = false;
  for (const fieldName of QUOTE_VEHICLE_INFO_FIELDS) {
    const value = String(payload[fieldName] ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
    if (!value) continue;
    vehicleInfo[fieldName] = value;
    hasAnyValue = true;
  }
  return hasAnyValue ? vehicleInfo : null;
}






function createQuoteKnownAnswerResolver(credentials) {
  return composeKnownAnswerResolvers(
    buildVehicleTechnicalAnswerResolver({ vin: credentials.vin, vehicleInfo: credentials.vehicleInfo }),
    answerStore.createResolver({ registration: credentials.registration, pesel: credentials.pesel }),
  );
}

function validateQuotePayload(payload, insurerName = "towarzystwa") {
  const registration = String(payload?.registration || "")
    .replace(/[^A-Z0-9]/gi, "")
    .toUpperCase()
    .slice(0, 12);
  const pesel = String(payload?.pesel || "").replace(/\D/g, "").slice(0, 11);
  const vin = String(payload?.vin || "").replace(/[^A-Z0-9]/gi, "").toUpperCase().slice(0, 24);
  const username = String(payload?.username || "").trim().slice(0, 120);
  const password = String(payload?.password || "").slice(0, 256);
  const vehicleInfo = sanitizeQuoteVehicleInfo(payload?.vehicleInfo);
  const manualMode = payload?.manualMode === true;
  const rawClientBatchId = String(payload?.clientBatchId || "").trim();
  const clientBatchId = normalizeClientQuoteBatchId(rawClientBatchId);
  if (registration.length < 4) throw new Error("Nieprawidłowy numer rejestracyjny.");
  if ((!manualMode || pesel) && !/^\d{11}$/.test(pesel)) throw new Error("Nieprawidłowy numer PESEL.");
  if (!username) throw new Error(`Brakuje loginu do ${insurerName}.`);
  if (rawClientBatchId && !clientBatchId) throw new Error("Nieprawidłowy identyfikator paczki kalkulacji.");
  return { registration, pesel, vin, username, password, vehicleInfo, clientBatchId, manualMode };
}

const MANUAL_OVERLAY_EDITABLE_FIELDS = new Set([
  "clientName",
  "identityNumber",
  "clientAddress",
  "clientPostalCode",
  "clientMaidenName",
  "clientPhone",
  "clientEmail",
  "vehicleMake",
  "vehicleModel",
  "vehicleType",
  "vin",
  "firstRegistrationDate",
  "productionYear",
  "fuelType",
  "engineCapacity",
  "enginePower",
  "seats",
  "grossWeight",
  "mileage",
  "driverLicenseDate",
]);
const MANUAL_OVERLAY_REQUEST_TIMEOUT_MS = 2 * 60 * 1000;
const manualOverlayRequests = new Map();

function requestManualOverlayAction(job, rawAction) {
  if (!job || job.kind !== "quote") {
    return Promise.resolve({ ok: false, error: "Ta karta nie jest powiązana z kalkulacją." });
  }
  const type = String(rawAction?.type || "");
  const fieldName = String(rawAction?.fieldName || "");
  const value = String(rawAction?.value || "").replace(/\s+/g, " ").trim().slice(0, 200);
  if (type === "save_missing" && (!MANUAL_OVERLAY_EDITABLE_FIELDS.has(fieldName) || !value)) {
    return Promise.resolve({ ok: false, error: "Sprawdź uzupełnianą wartość." });
  }
  if (type !== "save_missing" && type !== "vehicle_history") {
    return Promise.resolve({ ok: false, error: "Nieznana akcja okna danych." });
  }
  const id = randomUUID();
  return new Promise((resolve) => {
    const timeout = globalThis.setTimeout(() => {
      manualOverlayRequests.delete(id);
      resolve({
        ok: false,
        error: "Baza Polis nie potwierdziła zapisu na czas. Wróć do aplikacji i spróbuj ponownie.",
      });
    }, MANUAL_OVERLAY_REQUEST_TIMEOUT_MS);
    manualOverlayRequests.set(id, {
      id,
      jobId: job.id,
      insurerId: job.insurerId,
      registration: String(job.request?.registration || ""),
      pesel: String(job.request?.pesel || ""),
      type,
      fieldName: type === "save_missing" ? fieldName : "",
      value: type === "save_missing" ? value : "",
      createdAt: Date.now(),
      timeout,
      resolve,
    });
  });
}

function getPublicManualOverlayRequest(entry) {
  return {
    id: entry.id,
    registration: entry.registration,
    pesel: entry.pesel,
    type: entry.type,
    fieldName: entry.fieldName,
    value: entry.value,
    createdAt: entry.createdAt,
  };
}

function resolveManualOverlayRequest(id, result) {
  const entry = manualOverlayRequests.get(id);
  if (!entry) return false;
  manualOverlayRequests.delete(id);
  globalThis.clearTimeout(entry.timeout);
  entry.resolve({
    ok: result?.ok === true,
    error: String(result?.error || "").slice(0, 300),
    message: String(result?.message || "").slice(0, 180),
    vehicleInfo: sanitizeQuoteVehicleInfo(result?.vehicleInfo),
  });
  return true;
}

async function readJsonBody(request, { limit = MAX_REQUEST_BODY } = {}) {
  const chunks = [];
  let size = 0;
  for await (const chunk of request) {
    size += chunk.length;
    if (size > limit) throw new Error("Żądanie jest zbyt duże.");
    chunks.push(chunk);
  }
  try {
    return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
  } catch {
    throw new Error("Nieprawidłowe dane JSON.");
  }
}





const TRUSTED_APP_ORIGIN_HOST_PAIRS = new Map([
  [`http://${HOST}:${PORT}`, `${HOST}:${PORT}`],
  [`http://localhost:${PORT}`, `localhost:${PORT}`],
]);

function hasTrustedOriginHostPair(request) {
  const expectedHost = TRUSTED_APP_ORIGIN_HOST_PAIRS.get(request.headers.origin);
  return Boolean(expectedHost) && request.headers.host === expectedHost;
}

function isTrustedMutationRequest(request) {
  return hasTrustedOriginHostPair(request)
    && String(request.headers["content-type"] || "").toLowerCase().startsWith("application/json");
}





const PIN_SESSION_TTL_MS = 12 * 60 * 60 * 1000;
const PIN_SESSION_COOKIE = "sekagentSesja";
const PIN_SESSION_EXEMPT_PATHS = new Set([
  "/api/konto/status",
  "/api/konto/verify",
  "/api/konto/create",
  "/api/konto/set-pin",
]);


const LICENCJA_WOLNE_SCIEZKI = new Set([
  "/api/licencja/zapisz",
  "/api/licencja/usun",
  "/api/licencja/odswiez",
  "/api/konto/verify",
  "/api/konto/create",
  "/api/konto/set-pin",
  "/api/konto/lock",
  "/api/diagnostyka/zdarzenie",
  
  
  "/api/szyfr/przywroc-klucz",
  "/api/szyfr/potwierdz-ratunkowy",
]);

function isLicenseReadOnlyExemptPath(pathname) {
  return LICENCJA_WOLNE_SCIEZKI.has(pathname)
    
    
    || /^\/api\/automation\/jobs\/[a-f0-9-]+\/cancel$/i.test(pathname)
    || /^\/api\/automation\/quote-batches\/[a-z0-9][a-z0-9-]{7,79}\/cancel$/i.test(pathname)
    || /^\/api\/manual-quote\/overlay-actions\/[a-f0-9-]+\/resolve$/i.test(pathname);
}


function opisLicencjiDlaFrontu(stan) {
  if (!stan) return null;
  return {
    stan: stan.stan,
    tylkoOdczyt: stan.tylkoOdczyt === true,
    wazneDo: stan.wazneDo || "",
    dniDoKonca: Number.isFinite(stan.dniDoKonca) ? stan.dniDoKonca : null,
    nazwa: stan.nazwa || "",
    login: stan.login || "",
    komunikat: stan.komunikat || "",
    bladSprawdzenia: stan.bladSprawdzenia || "",
  };
}
const pinSessions = new Map();
let accountRequiresPinSession = true;

async function refreshAccountPinSessionFlag() {
  
  
  accountRequiresPinSession = true;
  const status = await kontoStore.getStatus({ strictExisting: true });
  accountRequiresPinSession = Boolean(status?.exists && status?.pinSet);
  return accountRequiresPinSession;
}

function issuePinSession(response) {
  const token = randomBytes(32).toString("hex");
  pinSessions.set(token, Date.now() + PIN_SESSION_TTL_MS);
  response.setHeader(
    "Set-Cookie",
    `${PIN_SESSION_COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/api`,
  );
  return token;
}

function getPinSessionToken(request) {
  const cookieHeader = String(request.headers.cookie || "");
  const match = cookieHeader.match(new RegExp(`(?:^|;\\s*)${PIN_SESSION_COOKIE}=([a-f0-9]{64})(?:;|$)`));
  return match?.[1] || "";
}

function hasValidPinSession(request) {
  const token = getPinSessionToken(request);
  if (!token) return false;
  const expiresAt = pinSessions.get(token);
  if (!expiresAt) return false;
  if (expiresAt <= Date.now()) {
    pinSessions.delete(token);
    return false;
  }
  pinSessions.set(token, Date.now() + PIN_SESSION_TTL_MS);
  return true;
}

function revokePinSession(request, response) {
  const token = getPinSessionToken(request);
  if (token) pinSessions.delete(token);
  response.setHeader(
    "Set-Cookie",
    `${PIN_SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/api; Max-Age=0`,
  );
}

function clearAllPinSessions() {
  pinSessions.clear();
}



function isTrustedBinaryUpload(request) {
  return hasTrustedOriginHostPair(request);
}




const MAX_SEED_REQUEST_BODY = 160 * 1024 * 1024;


async function readRequestBodyToFile(request, filePath, maxBytes) {
  const output = createWriteStream(filePath);
  let size = 0;
  try {
    for await (const chunk of request) {
      size += chunk.length;
      if (size > maxBytes) throw new Error("Paczka jest zbyt duża.");
      if (!output.write(chunk)) {
        await new Promise((resolveDrain) => output.once("drain", resolveDrain));
      }
    }
    await new Promise((resolveEnd, rejectEnd) => {
      output.end((error) => (error ? rejectEnd(error) : resolveEnd()));
    });
  } catch (error) {
    output.destroy();
    throw error;
  }
  if (size === 0) throw new Error("Przesłany plik jest pusty.");
}

function expandZipArchive(zipPath, destinationPath) {
  return new Promise((resolveExpand, rejectExpand) => {
    
    const child = spawn("powershell.exe", [
      "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command",
      "Expand-Archive -LiteralPath $env:BP_ZIP -DestinationPath $env:BP_DEST -Force",
    ], {
      env: { ...process.env, BP_ZIP: zipPath, BP_DEST: destinationPath },
      stdio: ["ignore", "ignore", "pipe"],
      windowsHide: true,
    });
    let stderrBytes = 0;
    child.stderr.on("data", (chunk) => {
      stderrBytes += chunk.length;
      if (stderrBytes > 16 * 1024) child.kill();
    });
    const timeout = globalThis.setTimeout(() => {
      child.kill();
      rejectExpand(new Error("Rozpakowywanie paczki trwało zbyt długo."));
    }, 180000);
    child.on("error", (error) => {
      globalThis.clearTimeout(timeout);
      rejectExpand(error);
    });
    child.on("exit", (code) => {
      globalThis.clearTimeout(timeout);
      if (code === 0) {
        resolveExpand();
      } else {
        rejectExpand(new Error("Nie udało się rozpakować paczki. Upewnij się, że wskazany plik to poprawna paczka ZIP."));
      }
    });
  });
}


async function readLargeRequestBody(request, maxBytes) {
  const chunks = [];
  let size = 0;
  for await (const chunk of request) {
    size += chunk.length;
    if (size > maxBytes) throw new Error("Przesłane dane są zbyt duże.");
    chunks.push(chunk);
  }
  return Buffer.concat(chunks).toString("utf8");
}


async function sendZipFile(response, zipPath, downloadName) {
  const zipStats = await stat(zipPath);
  applyCommonHeaders(response);
  response.statusCode = 200;
  response.setHeader("Content-Type", "application/zip");
  response.setHeader("Content-Length", zipStats.size);
  response.setHeader(
    "Content-Disposition",
    `attachment; filename="paczka.zip"; filename*=UTF-8''${encodeURIComponent(downloadName)}`,
  );
  await pipeStreamToHttpResponse(createReadStream(zipPath), response);
}

function sendPackageImportError(response, error) {
  const publicError = error instanceof PackageValidationError
    || error instanceof PackageImportTransactionError
    ? error
    : null;
  console.error(
    `Import paczki pracownika nie powiódł się (${publicError?.code || "PACKAGE_IMPORT_FAILED"}).`,
  );
  sendJson(response, publicError?.statusCode || 500, {
    error: publicError?.message || "Nie udało się bezpiecznie obsłużyć paczki pracownika.",
    ...(publicError ? { code: publicError.code } : {}),
    ...(publicError?.state === "rollback_blocked"
      ? { state: "rollback_blocked" }
      : {}),
  });
}

const PUBLIC_PAIRING_ERROR_CODES = new Set([
  "PAIRING_INVALID",
  "PAIRING_ACCOUNT",
  "PAIRING_TARGET_MISMATCH",
  "PAIRING_CONFLICT",
]);

function sendEmployeeAssignmentError(response, error, {
  fallback = "Nie udało się bezpiecznie obsłużyć paczki polis.",
} = {}) {
  if (error instanceof PackageValidationError || error instanceof PackageImportTransactionError) {
    sendPackageImportError(response, error);
    return;
  }
  const code = PUBLIC_PAIRING_ERROR_CODES.has(String(error?.code || ""))
    ? String(error.code)
    : "";
  const statusCode = code === "PAIRING_CONFLICT"
    ? 409
    : (code === "PAIRING_ACCOUNT" || code === "PAIRING_TARGET_MISMATCH" ? 403 : 400);
  console.error(`Obsługa przydziału polis nie powiodła się (${code || "ASSIGNMENT_FAILED"}).`);
  sendJson(response, code ? statusCode : 400, {
    error: code ? error.message : fallback,
    ...(code ? { code } : {}),
  });
}

async function readPackageImportActionBody(request) {
  let payload;
  try {
    payload = await readJsonBody(request, { limit: 1024 });
  } catch {
    throw new PackageImportTransactionError("PACKAGE_IMPORT_INVALID");
  }
  const keys = payload && typeof payload === "object" && !Array.isArray(payload)
    ? Object.keys(payload).sort()
    : [];
  if (
    keys.length !== 3
    || keys[0] !== "baseDigest"
    || keys[1] !== "packageDigest"
    || keys[2] !== "planDigest"
    || !/^[a-f0-9]{64}$/.test(String(payload.baseDigest || ""))
    || !/^[a-f0-9]{64}$/.test(String(payload.packageDigest || ""))
    || !/^[a-f0-9]{64}$/.test(String(payload.planDigest || ""))
  ) {
    throw new PackageImportTransactionError("PACKAGE_IMPORT_INVALID");
  }
  return {
    baseDigest: payload.baseDigest,
    packageDigest: payload.packageDigest,
    planDigest: payload.planDigest,
  };
}

async function runWartaJob(job, credentials, { forceManual = false } = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const manualStartOnly = credentials.manualMode === true && !forceManual;
    let loadedPortableRoute = await routeStore.loadRoute("warta");
    if (loadedPortableRoute && !wartaPathIncludesRecordSelection(loadedPortableRoute.formPath)) {
      await routeStore.deleteRoute("warta");
      loadedPortableRoute = null;
      updateJob(job, {
        status: "running",
        title: "Trasa Warty wymaga ponownego nagrania…",
        detail: "Nagraj trasę jeszcze raz - tym razem z wyborem rekordu.",
      });
    }
    let portableRoute = loadedPortableRoute || { formPath: [], resultPath: [] };
    const runInBackground = !forceManual && !manualStartOnly && Array.isArray(portableRoute.formPath)
      && portableRoute.formPath.length > 0;
    if (runInBackground) {
      updateJob(job, {
        status: "running",
        title: "Kalkulacja Warty w tle…",
        detail: "",
      });
    }
    let routeBackupDone = false;
    const premiums = await wartaAutomation.calculateQuote({
      ...credentials,
      navigationPath: portableRoute.formPath,
      formFields: portableRoute.formFields,
      resultNavigationPath: portableRoute.resultPath,
      runInBackground,
      async onPathLearned(path, fields) {
        portableRoute = await routeStore.saveRoute("warta", { ...portableRoute, formPath: path, formFields: fields }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      async onDiagnosticsCaptured(diagnostics, diagnosticsId = "warta") {
        await trainingDiagnosticsStore.save(diagnosticsId, diagnostics);
      },
      async onResultPathLearned(path) {
        portableRoute = await routeStore.saveRoute("warta", { ...portableRoute, resultPath: path }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      onInputRequested: createJobInputRequester(job),
      extraKnownAnswerResolver: createQuoteKnownAnswerResolver(credentials),
      manualStartOnly,
      onOverlayAction: (action) => requestManualOverlayAction(job, action),
      
      
      async onVehicleDataDiscovered(vehicleData) {
        try {
          if (job.watchdogExpired === true) return;
          job.vehicleData = mergeVehicleDataWithSource(
            job.vehicleData,
            { ...vehicleData, registration: credentials.registration },
            "warta-cepik",
          );
          const fields = [];
          const values = {};
          const addAnswer = (label, value) => {
            const cleanValue = String(value ?? "").trim();
            if (!cleanValue) return;
            
            
            
            const existing = answerStore.findAnswerForField({
              registration: credentials.registration,
              pesel: credentials.pesel,
              field: { label, kind: "text" },
            });
            if (existing) return;
            const id = `cepik-${fields.length + 1}`;
            fields.push({ id, label, kind: "text", options: [] });
            values[id] = cleanValue;
          };
          addAnswer("Data pierwszej rejestracji", vehicleData.firstRegistrationDate);
          addAnswer("Rok produkcji", vehicleData.productionYear);
          addAnswer("Pojemność silnika", vehicleData.engineCapacity);
          
          
          
          addAnswer("Moc silnika (kW)", vehicleData.enginePower);
          addAnswer("Rodzaj paliwa", vehicleData.fuel);
          addAnswer("Liczba miejsc", vehicleData.seats);
          addAnswer("DMC", vehicleData.grossWeight);
          if (fields.length > 0) {
            answerStore.recordAnswers({
              registration: credentials.registration,
              pesel: credentials.pesel,
              insurerId: "warta-cepik",
              fields,
              values,
            });
          }
        } catch (error) {
          console.error("Nie udało się zapisać danych pojazdu z Warty.", error?.message || error);
        }
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, manualStartOnly ? {
      status: "manual_ready",
      title: "Karta Warty gotowa do ręcznego liczenia",
      detail: "Dalsze dane wpisz bezpośrednio w kalkulatorze.",
      premiums: [],
      manualAvailable: false,
    } : {
      status: "completed",
      title: "Kalkulacja Warty zakończona",
      detail: "",
      premiums,
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "manual_required",
      title: "Warta wymaga poprawienia ręcznego",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueWartaJob(job, credentials, options = {}) {
  return enqueueAutomationJob(
    wartaQueue,
    job,
    () => runWartaJob(job, credentials, options),
  );
}


async function runWartaPortfolioRecordsJob(job, credentials) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const records = await wartaAutomation.importPortfolioRecords({
      ...credentials,
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, {
      status: "completed",
      title: "Wybierz rekord Warty do importu",
      detail: `Znaleziono ${records.length} rekordów. Wskaż z listy, z którego pobrać polisy.`,
      records,
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "error",
      title: "Nie udało się pobrać listy rekordów Warty",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: false,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueWartaPortfolioRecordsJob(job, credentials) {
  return enqueueAutomationJob(
    wartaQueue,
    job,
    () => runWartaPortfolioRecordsJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}


async function runWartaPortfolioJob(job, credentials) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "warta", {
      sourceAccount: credentials.username,
      portfolioId: job.agreementId,
    });
    let importOutcome = null;
    const policies = await wartaAutomation.importPortfolio({
      ...credentials,
      agreementId: job.agreementId,
      agreementLabel: job.agreementLabel,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      knownPdfPolicyNumbers: job.knownPolicyNumbers || [],
      sinceDate,
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "Warty" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || `warta:${job.agreementId}`, job, error);
    updateJob(job, {
      status: "error",
      title: "Import polis Warty nie powiódł się",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: false,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueWartaPortfolioJob(job, credentials) {
  return enqueueAutomationJob(
    wartaQueue,
    job,
    () => runWartaPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}




async function runPzuOpenJob(job, credentials = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const { loggedIn } = await pzuAutomation.openLogin({
      credentials,
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, {
      status: "completed",
      title: loggedIn ? "PZU jest już zalogowane" : "Zaloguj się w oknie PZU",
      detail: loggedIn
        ? "Możesz od razu kliknąć „Importuj polisy z PZU”."
        : "Zaloguj się w otwartym oknie, a potem wróć tutaj i kliknij „Importuj polisy z PZU”.",
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "error",
      title: "Nie udało się otworzyć okna PZU",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: false,
    });
  }
}

function enqueuePzuOpenJob(job, credentials = {}) {
  return enqueueAutomationJob(
    pzuQueue,
    job,
    () => runPzuOpenJob(job, credentials),
    { quoteTurnExempt: true },
  );
}



async function runPzuPortfolioJob(job, credentials = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "pzu", {
      sourceAccount: credentials.username,
      requireSourceAccountForIncremental: true,
    });
    let importOutcome = null;
    const policies = await pzuAutomation.importPortfolio({
      sinceDate,
      downloadPdfs,
      pdfDirectory,
      credentials,
      
      
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      knownPdfPolicyNumbers: job.knownPolicyNumbers || [],
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "PZU" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "pzu", job, error);
    updateJob(job, {
      status: "error",
      title: "Import polis PZU nie powiódł się",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: false,
    });
  }
}

function enqueuePzuPortfolioJob(job, credentials = {}) {
  return enqueueAutomationJob(
    pzuQueue,
    job,
    () => runPzuPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}




async function runInslyOpenJob(job, credentials = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const { loggedIn } = await inslyAutomation.openLogin({
      username: credentials.username || "",
      password: credentials.password || "",
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, {
      status: "completed",
      title: loggedIn ? "Superpolisa jest już zalogowana" : "Zaloguj się w oknie Superpolisy",
      detail: loggedIn
        ? "Możesz od razu kliknąć „Importuj polisy z Superpolisy”."
        : "Zaloguj się w otwartym oknie, a potem wróć tutaj i kliknij „Importuj polisy z Superpolisy”.",
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "error",
      title: "Nie udało się otworzyć okna Superpolisy",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: false,
    });
  }
}

function enqueueInslyOpenJob(job, credentials = {}) {
  return enqueueAutomationJob(
    inslyQueue,
    job,
    () => runInslyOpenJob(job, credentials),
    { quoteTurnExempt: true },
  );
}




async function runInslyPortfolioJob(job, credentials = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "insly", {
      sourceAccount: credentials.username,
      requireSourceAccountForIncremental: true,
    });
    let importOutcome = null;
    const policies = await inslyAutomation.importPortfolio({
      username: credentials.username || "",
      password: credentials.password || "",
      sinceDate,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyKeys: job.skipPdfPolicyKeys || [],
      knownPdfPolicyKeys: job.knownPdfPolicyKeys || [],
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "Superpolisy" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "insly", job, error);
    updateJob(job, {
      status: "error",
      title: "Import polis z Superpolisy nie powiódł się",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: false,
    });
  }
}

function enqueueInslyPortfolioJob(job, credentials = {}) {
  return enqueueAutomationJob(
    inslyQueue,
    job,
    () => runInslyPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}

async function runGeneraliJob(job, credentials, { forceManual = false } = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const manualStartOnly = credentials.manualMode === true && !forceManual;
    const loadedPortableRoute = await routeStore.loadRoute("generali");
    let portableRoute = loadedPortableRoute || { formPath: [], resultPath: [] };
    const runInBackground = !forceManual && !manualStartOnly && Array.isArray(portableRoute.formPath)
      && portableRoute.formPath.length > 0;
    if (runInBackground) {
      updateJob(job, {
        status: "running",
        title: "Kalkulacja Generali w tle…",
        detail: "",
      });
    }
    let routeBackupDone = false;
    const premiums = await generaliAutomation.calculateQuote({
      ...credentials,
      navigationPath: portableRoute.formPath,
      formFields: portableRoute.formFields,
      resultNavigationPath: portableRoute.resultPath,
      runInBackground,
      async onPathLearned(path, fields) {
        portableRoute = await routeStore.saveRoute("generali", { ...portableRoute, formPath: path, formFields: fields }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      async onDiagnosticsCaptured(diagnostics) {
        await trainingDiagnosticsStore.save("generali", diagnostics);
      },
      async onResultPathLearned(path) {
        portableRoute = await routeStore.saveRoute("generali", { ...portableRoute, resultPath: path }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      onInputRequested: createJobInputRequester(job),
      extraKnownAnswerResolver: createQuoteKnownAnswerResolver(credentials),
      manualStartOnly,
      onOverlayAction: (action) => requestManualOverlayAction(job, action),
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, manualStartOnly ? {
      status: "manual_ready",
      title: "Karta Generali gotowa do ręcznego liczenia",
      detail: "Dalsze dane wpisz bezpośrednio w kalkulatorze.",
      premiums: [],
      manualAvailable: false,
    } : {
      status: "completed",
      title: "Kalkulacja Generali zakończona",
      detail: "",
      premiums,
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "manual_required",
      title: "Generali wymaga poprawienia ręcznego",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueGeneraliJob(job, credentials, options = {}) {
  return enqueueAutomationJob(
    generaliQueue,
    job,
    () => runGeneraliJob(job, credentials, options),
  );
}

async function runMtuJob(job, credentials, { forceManual = false } = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const manualStartOnly = credentials.manualMode === true && !forceManual;
    const loadedPortableRoute = await routeStore.loadRoute("mtu");
    let portableRoute = loadedPortableRoute || { formPath: [], resultPath: [] };
    const runInBackground = !forceManual && !manualStartOnly && Array.isArray(portableRoute.formPath)
      && portableRoute.formPath.length > 0;
    if (runInBackground) {
      updateJob(job, {
        status: "running",
        title: "Kalkulacja MTU w tle…",
        detail: "",
      });
    }
    let routeBackupDone = false;
    const premiums = await mtuAutomation.calculateQuote({
      ...credentials,
      runInBackground,
      navigationPath: portableRoute.formPath,
      formFields: portableRoute.formFields,
      resultNavigationPath: portableRoute.resultPath,
      async onPathLearned(path, fields) {
        portableRoute = await routeStore.saveRoute("mtu", { ...portableRoute, formPath: path, formFields: fields }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      async onDiagnosticsCaptured(diagnostics) {
        await trainingDiagnosticsStore.save("mtu", diagnostics);
      },
      async onResultPathLearned(path) {
        portableRoute = await routeStore.saveRoute("mtu", { ...portableRoute, resultPath: path }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      onInputRequested: createJobInputRequester(job),
      extraKnownAnswerResolver: createQuoteKnownAnswerResolver(credentials),
      manualStartOnly,
      onOverlayAction: (action) => requestManualOverlayAction(job, action),
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, manualStartOnly ? {
      status: "manual_ready",
      title: "Karta MTU gotowa do ręcznego liczenia",
      detail: "Dalsze dane wpisz bezpośrednio w kalkulatorze.",
      premiums: [],
      manualAvailable: false,
    } : {
      status: "completed",
      title: "Kalkulacja MTU zakończona",
      detail: "",
      premiums,
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "manual_required",
      title: "MTU wymaga poprawienia ręcznego",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueMtuJob(job, credentials, options = {}) {
  return enqueueAutomationJob(
    mtuQueue,
    job,
    () => runMtuJob(job, credentials, options),
  );
}

async function runMtuPortfolioJob(job, credentials, { forceManual = false } = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const loadedPortableRoute = await routeStore.loadRoute("mtu-portfel");
    let portableRoute = loadedPortableRoute || { formPath: [], resultPath: [] };
    
    
    const runInBackground = !forceManual;
    if (runInBackground) {
      updateJob(job, {
        status: "running",
        title: "Import polis MTU w tle…",
        detail: "",
      });
    }
    let routeBackupDone = false;
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "mtu", {
      sourceAccount: credentials.username,
    });
    let importOutcome = null;
    const policies = await mtuAutomation.importPortfolio({
      ...credentials,
      runInBackground,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      knownPdfPolicyNumbers: job.knownPolicyNumbers || [],
      pdfBacklogOnly: job.pdfBacklogOnly === true,
      pdfBacklogPolicyNumbers: job.pdfBacklogPolicyNumbers || [],
      sinceDate,
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      navigationPath: portableRoute.formPath,
      async onPathLearned(path) {
        portableRoute = await routeStore.saveRoute("mtu-portfel", { ...portableRoute, formPath: path }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      async onDiagnosticsCaptured(diagnostics, diagnosticsId = "mtu-portfel") {
        await trainingDiagnosticsStore.save(diagnosticsId, diagnostics);
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "MTU" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "mtu", job, error);
    updateJob(job, {
      status: "manual_required",
      title: "Import polis MTU wymaga poprawienia ścieżki",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueMtuPortfolioJob(job, credentials, options = {}) {
  return enqueueAutomationJob(
    mtuQueue,
    job,
    () => runMtuPortfolioJob(job, credentials, options),
    { waitForPortfolioTurn: true },
  );
}

async function runHestiaPortfolioJob(job, credentials) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "hestia", {
      sourceAccount: credentials.username,
    });
    let importOutcome = null;
    const policies = await hestiaAutomation.importPortfolio({
      ...credentials,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      knownPdfPolicyNumbers: job.knownPolicyNumbers || [],
      pdfBacklogOnly: job.pdfBacklogOnly === true,
      pdfBacklogPolicyNumbers: job.pdfBacklogPolicyNumbers || [],
      sinceDate,
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "Ergo Hestii" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "hestia", job, error);
    updateJob(job, {
      status: "manual_required",
      title: "Import polis Ergo Hestii wymaga poprawienia ścieżki",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueHestiaPortfolioJob(job, credentials) {
  return enqueueAutomationJob(
    hestiaQueue,
    job,
    () => runHestiaPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}

async function runWienerPortfolioJob(job, credentials) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "wiener", {
      sourceAccount: credentials.username,
    });
    let importOutcome = null;
    const policies = await wienerAutomation.importPortfolio({
      ...credentials,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      knownPdfPolicyNumbers: job.knownPolicyNumbers || [],
      sinceDate,
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "Wiener" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "wiener", job, error);
    updateJob(job, {
      status: "manual_required",
      title: "Import polis Wiener wymaga poprawienia ścieżki",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueWienerPortfolioJob(job, credentials) {
  return enqueueAutomationJob(
    wienerQueue,
    job,
    () => runWienerPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}

async function runGeneraliPortfolioJob(job, credentials) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "generali", {
      sourceAccount: credentials.username,
    });
    let importOutcome = null;
    const policies = await generaliAutomation.importPortfolio({
      ...credentials,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      knownPdfPolicyNumbers: job.knownPolicyNumbers || [],
      sinceDate,
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      
      
      onInputRequested: createPortfolioInputRequester(job),
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "Generali" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "generali", job, error);
    updateJob(job, {
      status: "manual_required",
      title: "Import polis Generali wymaga poprawienia ścieżki",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueGeneraliPortfolioJob(job, credentials) {
  return enqueueAutomationJob(
    generaliQueue,
    job,
    () => runGeneraliPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}

async function runTrastiJob(job, credentials, { forceManual = false } = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const manualStartOnly = credentials.manualMode === true && !forceManual;
    const loadedPortableRoute = await routeStore.loadRoute("trasti");
    let portableRoute = loadedPortableRoute || { formPath: [], resultPath: [] };
    const runInBackground = !forceManual && !manualStartOnly && Array.isArray(portableRoute.formPath)
      && portableRoute.formPath.length > 0;
    if (runInBackground) {
      updateJob(job, {
        status: "running",
        title: "Kalkulacja Trasti w tle…",
        detail: "",
      });
    }
    let routeBackupDone = false;
    const premiums = await trastiAutomation.calculateQuote({
      ...credentials,
      navigationPath: portableRoute.formPath,
      formFields: portableRoute.formFields,
      resultNavigationPath: portableRoute.resultPath,
      runInBackground,
      async onPathLearned(path, fields) {
        portableRoute = await routeStore.saveRoute("trasti", { ...portableRoute, formPath: path, formFields: fields }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      async onDiagnosticsCaptured(diagnostics) {
        await trainingDiagnosticsStore.save("trasti", diagnostics);
      },
      async onResultPathLearned(path) {
        portableRoute = await routeStore.saveRoute("trasti", { ...portableRoute, resultPath: path }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      onInputRequested: createJobInputRequester(job),
      extraKnownAnswerResolver: createQuoteKnownAnswerResolver(credentials),
      manualStartOnly,
      onOverlayAction: (action) => requestManualOverlayAction(job, action),
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, manualStartOnly ? {
      status: "manual_ready",
      title: "Karta Trasti gotowa do ręcznego liczenia",
      detail: "Dalsze dane wpisz bezpośrednio w kalkulatorze.",
      premiums: [],
      manualAvailable: false,
    } : {
      status: "completed",
      title: "Kalkulacja Trasti zakończona",
      detail: "",
      premiums,
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "manual_required",
      title: "Trasti wymaga poprawienia ręcznego",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueTrastiJob(job, credentials, options = {}) {
  return enqueueAutomationJob(
    trastiQueue,
    job,
    () => runTrastiJob(job, credentials, options),
  );
}

async function runTrastiPortfolioJob(job, credentials) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "trasti", {
      sourceAccount: credentials.username,
    });
    let importOutcome = null;
    const policies = await trastiAutomation.importPortfolio({
      ...credentials,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      knownPdfPolicyNumbers: job.knownPolicyNumbers || [],
      sinceDate,
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "Trasti" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "trasti", job, error);
    updateJob(job, {
      status: "manual_required",
      title: "Import polis Trasti wymaga poprawienia ścieżki",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueTrastiPortfolioJob(job, credentials) {
  return enqueueAutomationJob(
    trastiQueue,
    job,
    () => runTrastiPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}

async function runWienerJob(job, credentials, { forceManual = false } = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const manualStartOnly = credentials.manualMode === true && !forceManual;
    const loadedPortableRoute = await routeStore.loadRoute("wiener");
    let portableRoute = loadedPortableRoute || { formPath: [], resultPath: [] };
    const runInBackground = !forceManual && !manualStartOnly && Array.isArray(portableRoute.formPath)
      && portableRoute.formPath.length > 0;
    if (runInBackground) {
      updateJob(job, {
        status: "running",
        title: "Kalkulacja Wiener w tle…",
        detail: "",
      });
    }
    let routeBackupDone = false;
    const premiums = await wienerAutomation.calculateQuote({
      ...credentials,
      navigationPath: portableRoute.formPath,
      formFields: portableRoute.formFields,
      resultNavigationPath: portableRoute.resultPath,
      runInBackground,
      async onPathLearned(path, fields) {
        portableRoute = await routeStore.saveRoute("wiener", { ...portableRoute, formPath: path, formFields: fields }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      async onDiagnosticsCaptured(diagnostics) {
        await trainingDiagnosticsStore.save("wiener", diagnostics);
      },
      async onResultPathLearned(path) {
        portableRoute = await routeStore.saveRoute("wiener", { ...portableRoute, resultPath: path }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      onInputRequested: createJobInputRequester(job),
      extraKnownAnswerResolver: createQuoteKnownAnswerResolver(credentials),
      manualStartOnly,
      onOverlayAction: (action) => requestManualOverlayAction(job, action),
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, manualStartOnly ? {
      status: "manual_ready",
      title: "Karta Wiener gotowa do ręcznego liczenia",
      detail: "Dalsze dane wpisz bezpośrednio w kalkulatorze.",
      premiums: [],
      manualAvailable: false,
    } : {
      status: "completed",
      title: "Kalkulacja Wiener zakończona",
      detail: "",
      premiums,
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "manual_required",
      title: "Wiener wymaga poprawienia ręcznego",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

async function runCompensaPortfolioJob(job, credentials) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie\u2026",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "compensa", {
      sourceAccount: credentials.username,
    });
    let importOutcome = null;
    const policies = await compensaAutomation.importPortfolio({
      ...credentials,
      sinceDate,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "Compensa" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "compensa", job, error);
    updateJob(job, {
      status: "manual_required",
      title: "Import polis Compensa wymaga poprawienia \u015bcie\u017cki",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueCompensaPortfolioJob(job, credentials) {
  return enqueueAutomationJob(
    compensaQueue,
    job,
    () => runCompensaPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}

async function runAllianzPortfolioJob(job, credentials) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const downloadPdfs = job.downloadPdfs === true;
    let pdfDirectory = "";
    if (downloadPdfs) {
      pdfDirectory = await preparePortfolioPdfJobDirectory(job.id);
      job.pdfDirectory = pdfDirectory;
    }
    const { stateKey, sinceDate } = await initializePortfolioCheckpoint(job, "allianz", {
      sourceAccount: credentials.username,
    });
    let importOutcome = null;
    const policies = await allianzAutomation.importPortfolio({
      ...credentials,
      sinceDate,
      downloadPdfs,
      pdfDirectory,
      pdfPolicyLimit: drawPdfPolicyLimit(),
      skipPdfPolicyNumbers: job.skipPdfPolicyNumbers || [],
      knownPdfPolicyNumbers: job.knownPolicyNumbers || [],
      onCompletion(outcome) {
        importOutcome = outcome && typeof outcome === "object" ? outcome : null;
      },
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    job.pdfRetry = importOutcome?.pdfRetry || null;
    job.pdfRetryIdentities = Array.isArray(importOutcome?.pdfRetryIdentities)
      ? importOutcome.pdfRetryIdentities
      : [];
    await completePortfolioImportJob(job, { stateKey, sinceDate, policies, outcome: importOutcome, insurerLabel: "Allianz" });
  } catch (error) {
    recordPortfolioImportFailure(job.portfolioStateKey || "allianz", job, error);
    updateJob(job, {
      status: "manual_required",
      title: "Import polis Allianz wymaga poprawienia ścieżki",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueAllianzPortfolioJob(job, credentials) {
  return enqueueAutomationJob(
    allianzQueue,
    job,
    () => runAllianzPortfolioJob(job, credentials),
    { waitForPortfolioTurn: true },
  );
}

async function runAllianzJob(job, credentials, { forceManual = false } = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie…",
    detail: "",
  });
  try {
    const manualStartOnly = credentials.manualMode === true && !forceManual;
    
    
    if (!forceManual && !manualStartOnly) {
      updateJob(job, {
        status: "running",
        title: "Kalkulacja Allianz w tle…",
        detail: "",
      });
    }
    const premiums = await allianzAutomation.calculateQuote({
      ...credentials,
      runInBackground: !forceManual && !manualStartOnly,
      manualStartOnly,
      onOverlayAction: (action) => requestManualOverlayAction(job, action),
      onInputRequested: createJobInputRequester(job),
      extraKnownAnswerResolver: createQuoteKnownAnswerResolver(credentials),
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, manualStartOnly ? {
      status: "manual_ready",
      title: "Karta Allianz gotowa do ręcznego liczenia",
      detail: "Dalsze dane wpisz bezpośrednio w kalkulatorze.",
      premiums: [],
      manualAvailable: false,
    } : {
      status: "completed",
      title: "Kalkulacja Allianz zakończona",
      detail: "",
      premiums,
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "manual_required",
      title: "Allianz wymaga poprawienia ręcznego",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueAllianzJob(job, credentials, options = {}) {
  return enqueueAutomationJob(
    allianzQueue,
    job,
    () => runAllianzJob(job, credentials, options),
  );
}

async function runCompensaJob(job, credentials, { forceManual = false } = {}) {
  updateJob(job, {
    status: "running",
    title: "Uruchamianie\u2026",
    detail: "",
  });
  try {
    const manualStartOnly = credentials.manualMode === true && !forceManual;
    const loadedPortableRoute = await routeStore.loadRoute("compensa");
    let portableRoute = loadedPortableRoute || { formPath: [], resultPath: [] };
    const runInBackground = !forceManual && !manualStartOnly && Array.isArray(portableRoute.formPath)
      && portableRoute.formPath.length > 0;
    if (runInBackground) {
      updateJob(job, {
        status: "running",
        title: "Kalkulacja Compensa w tle\u2026",
        detail: "",
      });
    }
    let routeBackupDone = false;
    const premiums = await compensaAutomation.calculateQuote({
      ...credentials,
      navigationPath: portableRoute.formPath,
      formFields: portableRoute.formFields,
      resultNavigationPath: portableRoute.resultPath,
      runInBackground,
      async onPathLearned(path, fields) {
        portableRoute = await routeStore.saveRoute("compensa", { ...portableRoute, formPath: path, formFields: fields }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      async onDiagnosticsCaptured(diagnostics) {
        await trainingDiagnosticsStore.save("compensa", diagnostics);
      },
      async onResultPathLearned(path) {
        portableRoute = await routeStore.saveRoute("compensa", { ...portableRoute, resultPath: path }, { backup: !routeBackupDone });
        routeBackupDone = true;
        updateJob(job, { navigationLearned: true });
      },
      onInputRequested: createJobInputRequester(job),
      extraKnownAnswerResolver: createQuoteKnownAnswerResolver(credentials),
      manualStartOnly,
      onOverlayAction: (action) => requestManualOverlayAction(job, action),
      onProgress(progress) {
        updateJob(job, {
          status: progress.status || "running",
          title: progress.title || job.title,
          detail: progress.detail || "",
        });
      },
    });
    updateJob(job, manualStartOnly ? {
      status: "manual_ready",
      title: "Karta Compensy gotowa do r\u0119cznego liczenia",
      detail: "Dalsze dane wpisz bezpo\u015brednio w kalkulatorze.",
      premiums: [],
      manualAvailable: false,
    } : {
      status: "completed",
      title: "Kalkulacja Compensa zako\u0144czona",
      detail: "",
      premiums,
      manualAvailable: false,
    });
  } catch (error) {
    updateJob(job, {
      status: "manual_required",
      title: "Compensa wymaga poprawienia r\u0119cznego",
      detail: friendlyAutomationErrorDetail(error),
      manualAvailable: true,
    });
  } finally {
    credentials.password = "";
  }
}

function enqueueCompensaJob(job, credentials, options = {}) {
  return enqueueAutomationJob(
    compensaQueue,
    job,
    () => runCompensaJob(job, credentials, options),
  );
}

function enqueueWienerJob(job, credentials, options = {}) {
  return enqueueAutomationJob(
    wienerQueue,
    job,
    () => runWienerJob(job, credentials, options),
  );
}




function zapiszHistoriePojazduDoMagazynu({ registration, pesel, firstRegistrationDate }, pojazd) {
  if (!pesel) return;
  try {
    const fields = [];
    const values = {};
    const addAnswer = (label, value) => {
      const cleanValue = String(value ?? "").trim();
      if (!cleanValue) return;
      const existing = answerStore.findAnswerForField({
        registration,
        pesel,
        field: { label, kind: "text" },
      });
      if (existing) return;
      const id = `historiapojazdu-${fields.length + 1}`;
      fields.push({ id, label, kind: "text", options: [] });
      values[id] = cleanValue;
    };
    addAnswer("Data pierwszej rejestracji", firstRegistrationDate);
    addAnswer("Rok produkcji", pojazd.yearOfManufacture);
    addAnswer("Pojemność silnika", pojazd.engineCapacity);
    
    addAnswer("Moc silnika (kW)", pojazd.enginePower);
    addAnswer("Rodzaj paliwa", pojazd.fuelType);
    addAnswer("Liczba miejsc", pojazd.seats);
    addAnswer("DMC", pojazd.grossWeight);
    addAnswer("Rodzaj pojazdu", pojazd.vehicleType);
    if (fields.length > 0) {
      answerStore.recordAnswers({
        registration,
        pesel,
        insurerId: "historiapojazdu-cepik",
        fields,
        values,
      });
    }
  } catch (error) {
    console.error("Nie udało się zapisać danych pojazdu z HistoriaPojazdu.gov.", error?.message || error);
  }
}

async function handleApiRequest(request, response, url) {
  
  if (
    accountRequiresPinSession
    && !PIN_SESSION_EXEMPT_PATHS.has(url.pathname)
    && !hasValidPinSession(request)
  ) {
    sendJson(response, 401, {
      code: "PIN_SESSION_REQUIRED",
      error: "Sesja wygasła. Podaj PIN ponownie.",
    });
    return true;
  }

  
  
  if (request.method !== "GET" && !isLicenseReadOnlyExemptPath(url.pathname)) {
    const stanLicencji = await licencjaProgramu.zapewnijStan().catch(() => null);
    if (stanLicencji?.tylkoOdczyt) {
      sendJson(response, 402, {
        code: "LICENCJA_TYLKO_ODCZYT",
        error: stanLicencji.komunikat || "Licencja programu jest nieważna. Program działa tylko do odczytu.",
        licencja: opisLicencjiDlaFrontu(stanLicencji),
      });
      return true;
    }
  }

  
  
  
  if (request.method === "GET" && url.pathname === "/api/szyfr/status") {
    sendJson(response, 200, {
      stan: szyfrBazy.stan(),
      ratunkowyPotwierdzony: szyfrBazy.ratunkowyPotwierdzony(),
      depozytUProducenta: szyfrBazy.depozytAktualny(),
    });
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/szyfr/klucz-bazy") {
    if (szyfrBazy.aktywny()) {
      sendJson(response, 200, {
        aktywny: true,
        klucz: szyfrBazy.klucz().toString("base64"),
        ratunkowyPotwierdzony: szyfrBazy.ratunkowyPotwierdzony(),
        depozytUProducenta: szyfrBazy.depozytAktualny(),
      });
    } else if (szyfrBazy.stan() === "nieodczytany") {
      sendJson(response, 200, { aktywny: true, klucz: null, wymagaPrzywrocenia: true });
    } else {
      sendJson(response, 200, { aktywny: false });
    }
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/szyfr/klucz-ratunkowy") {
    const kluczRatunkowy = szyfrBazy.kluczRatunkowyHex();
    if (!kluczRatunkowy) {
      sendJson(response, 409, { error: "Szyfrowanie bazy nie jest aktywne." });
      return true;
    }
    sendJson(response, 200, {
      klucz: kluczRatunkowy,
      ratunkowyPotwierdzony: szyfrBazy.ratunkowyPotwierdzony(),
    });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/szyfr/potwierdz-ratunkowy") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await szyfrBazy.potwierdzRatunkowy();
      sendJson(response, 200, { ok: true });
    } catch (error) {
      console.error("Szyfr bazy: nie udało się zapisać potwierdzenia klucza ratunkowego.", error?.message || error);
      sendJson(response, 500, { error: "Nie udało się zapisać potwierdzenia. Spróbuj ponownie." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/szyfr/przywroc-klucz") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    let body;
    try {
      body = await readJsonBody(request);
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nieprawidłowe dane." });
      return true;
    }
    const kluczRatunkowyHex = normalizujKluczRatunkowy(body?.klucz);
    if (!kluczRatunkowyHex) {
      sendJson(response, 400, { error: "Klucz ratunkowy ma nieprawidłową postać. Sprawdź, czy przepisano wszystkie 64 znaki." });
      return true;
    }
    
    
    const kandydat = Buffer.from(kluczRatunkowyHex, "hex");
    const sciezkiDoSprawdzenia = [
      join(ROOT_DIRECTORY, "polisy-dane.json"),
      join(ROOT_DIRECTORY, "polisy-odpowiedzi.json"),
    ];
    let sprawdzono = false;
    for (const sciezka of sciezkiDoSprawdzenia) {
      let bytes = null;
      try {
        bytes = await readFile(sciezka);
      } catch {
        continue;
      }
      if (!czyZaszyfrowanaBaza(bytes)) continue;
      try {
        odszyfrujBuforBazy(kandydat, bytes);
        sprawdzono = true;
      } catch {
        sendJson(response, 400, { error: "Ten klucz ratunkowy nie pasuje do tej bazy." });
        return true;
      }
      break;
    }
    if (!sprawdzono) {
      sendJson(response, 400, {
        error: "Nie ma tu zaszyfrowanych danych, do których pasowałby ten klucz. Otwórz najpierw folder z bazą polis.",
      });
      return true;
    }
    try {
      await szyfrBazy.przywrocZRatunkowego(kluczRatunkowyHex);
      const wynikMigracji = await migrujPlikiBazyDoSzyfru({
        rootDirectory: ROOT_DIRECTORY,
        key: szyfrBazy.klucz(),
      }).catch(() => null);
      for (const wpis of wynikMigracji?.bledy || []) {
        console.error("Szyfr bazy - migracja po przywróceniu klucza:", wpis);
      }
      if (typeof answerStore.reinit === "function") {
        await answerStore.reinit().catch(() => {});
      }
      sendJson(response, 200, { ok: true });
    } catch (error) {
      console.error("Szyfr bazy: nie udało się przywrócić klucza.", error?.message || error);
      sendJson(response, 500, { error: "Nie udało się zapisać klucza na tym komputerze. Spróbuj ponownie." });
    }
    return true;
  }

  
  
  
  
  
  
  
  
  if (request.method === "POST" && /^\/api\/[a-z0-9-]+\/portfolio(\/|$)/.test(url.pathname)) {
    if (!(await kontoStore.isPortfolioImportAllowed())) {
      sendJson(response, 403, { error: "Centrala nie włączyła importu polis z towarzystw dla tej bazy. Polisy dodasz ręcznie albo z plików PDF." });
      return true;
    }
  }

  
  
  
  if (request.method === "GET" && url.pathname === "/api/manual-quote/overlay-actions") {
    sendJson(response, 200, {
      requests: [...manualOverlayRequests.values()]
        .sort((first, second) => first.createdAt - second.createdAt)
        .map(getPublicManualOverlayRequest),
    });
    return true;
  }

  const manualOverlayResolveMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/manual-quote\/overlay-actions\/([a-f0-9-]+)\/resolve$/i);
  if (manualOverlayResolveMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    const payload = await readJsonBody(request);
    if (!resolveManualOverlayRequest(manualOverlayResolveMatch[1], payload)) {
      sendJson(response, 404, { error: "To żądanie zapisu już wygasło." });
      return true;
    }
    sendJson(response, 200, { ok: true });
    return true;
  }

  
  
  
  if (request.method === "GET" && url.pathname === "/api/diagnostyka") {
    sendJson(response, 200, await diagnostykaStore.odczytaj());
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/diagnostyka/zdarzenie") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const zapisano = await diagnostykaStore.zapiszZdarzenie(payload?.rodzaj, payload?.dane);
      if (!zapisano) {
        sendJson(response, 400, { error: "Nieobsługiwany rodzaj zdarzenia diagnostycznego." });
        return true;
      }
      sendJson(response, 200, { ok: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się zapisać zdarzenia." });
    }
    return true;
  }

  
  
  
  if (request.method === "POST" && url.pathname === "/api/zalaczniki/pdf") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: 64 * 1024 });
      const results = await policyPdfReader.readPolicyPdfs(payload?.files);
      sendJson(response, 200, { results });
    } catch (error) {
      
      
      console.error("Odczyt PDF-ów polis nie powiódł się:", error?.message || error);
      sendJson(response, 503, { error: "Nie udało się przeczytać plików polis." });
    }
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/konto/status") {
    const [status, motyw] = await Promise.all([
      kontoStore.getStatus(),
      odczytajMotywStartowy(),
    ]);
    sendJson(response, 200, {
      ...status,
      motyw,
      authenticated: accountRequiresPinSession ? hasValidPinSession(request) : true,
    });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/lock") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    revokePinSession(request, response);
    sendJson(response, 200, { locked: true });
    return true;
  }

  
  if (request.method === "GET" && url.pathname === "/api/konto/snapshot") {
    sendJson(response, 200, await kontoStore.getSnapshot());
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/create") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      await kontoStore.createAccount({
        name: payload?.name,
        pin: payload?.pin,
        servedInsurers: payload?.servedInsurers,
      });
      diagnostykaStore.zapiszZdarzenie("konto-utworzone");
      await refreshAccountPinSessionFlag();
      if (accountRequiresPinSession) issuePinSession(response);
      sendJson(response, 200, await kontoStore.getSnapshot());
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się założyć konta." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/verify") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const verification = await kontoStore.verifyPin(payload?.pin);
      if (!verification.ok) {
        sendJson(response, 401, verification);
        return true;
      }
      issuePinSession(response);
      sendJson(response, 200, { ok: true, authenticated: true, ...(await kontoStore.getSnapshot()) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się sprawdzić PIN-u." });
    }
    return true;
  }

  
  if (request.method === "POST" && url.pathname === "/api/konto/set-pin") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      await kontoStore.setInitialPin(payload?.pin);
      await refreshAccountPinSessionFlag();
      if (accountRequiresPinSession) issuePinSession(response);
      sendJson(response, 200, { ok: true, ...(await kontoStore.getSnapshot()) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się ustawić PIN-u." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/change-pin") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      await kontoStore.changePin(payload?.currentPin, payload?.newPin);
      
      
      clearAllPinSessions();
      await refreshAccountPinSessionFlag();
      if (accountRequiresPinSession) issuePinSession(response);
      sendJson(response, 200, { changed: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się zmienić PIN-u." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/name") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      await kontoStore.renameAccount(payload?.name);
      diagnostykaStore.zapiszZdarzenie("zmiana-nazwy-konta");
      sendJson(response, 200, await kontoStore.getSnapshot());
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się zmienić nazwy konta." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/towarzystwa") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      await kontoStore.setServedInsurers(payload?.servedInsurers);
      sendJson(response, 200, await kontoStore.getSnapshot());
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się zapisać towarzystw agencji." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/pracownicy") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      await kontoStore.addMember({ id: payload?.id, label: payload?.label });
      sendJson(response, 200, await kontoStore.getSnapshot());
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się dodać pracownika." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/pracownicy/etykieta") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      await kontoStore.updateMemberLabel(payload?.id, payload?.label);
      sendJson(response, 200, await kontoStore.getSnapshot());
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się zmienić nazwy pracownika." });
    }
    return true;
  }

  const memberPairingMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/konto\/pracownicy\/([A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4})\/parowanie$/);
  if (memberPairingMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: 1024 });
      if (
        !payload
        || typeof payload !== "object"
        || Array.isArray(payload)
        || Object.keys(payload).length !== 0
      ) {
        const invalid = new Error("Żądanie parowania jest nieprawidłowe.");
        invalid.code = "PAIRING_INVALID";
        throw invalid;
      }
      const credentials = await kontoStore.ensureMemberTransferCredentials(memberPairingMatch[1]);
      const pairingCode = formatAgencyPairingCode(credentials);
      sendJson(response, 200, { pairingCode });
    } catch (error) {
      sendEmployeeAssignmentError(response, error, {
        fallback: "Nie udało się przygotować kodu parowania.",
      });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/parowanie-centrali") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: 1024 });
      const keys = payload && typeof payload === "object" && !Array.isArray(payload)
        ? Object.keys(payload)
        : [];
      if (keys.length !== 1 || keys[0] !== "pairingCode" || typeof payload.pairingCode !== "string") {
        const invalid = new Error("Żądanie parowania jest nieprawidłowe.");
        invalid.code = "PAIRING_INVALID";
        throw invalid;
      }
      await kontoStore.pairCentralAccount(payload.pairingCode);
      sendJson(response, 200, {
        ok: true,
        ...(await kontoStore.getSnapshot()),
      });
    } catch (error) {
      sendEmployeeAssignmentError(response, error, {
        fallback: "Nie udało się połączyć konta z centralą.",
      });
    }
    return true;
  }

  
  
  if (request.method === "POST" && url.pathname === "/api/konto/paczka-pracownika") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    let generatedEmployee = null;
    let packageDelivered = false;
    try {
      
      
      
      const payload = await readJsonBody(request, { limit: MAX_SEED_REQUEST_BODY });
      const databaseContents = typeof payload?.databaseContents === "string"
        ? payload.databaseContents
        : "";
      generatedEmployee = await kontoStore.registerGeneratedEmployee(payload?.label);
      const agencySnapshot = await kontoStore.getSnapshot();
      const employeePackage = await buildEmployeePackage({
        rootDirectory: ROOT_DIRECTORY,
        filesDirectory: FILES_DIRECTORY,
        employee: generatedEmployee,
        servedInsurers: agencySnapshot.account?.servedInsurers,
        
        allowInsurerImports: payload?.allowInsurerImports === true,
        nodeExecutablePath: process.execPath,
        databaseContents,
      });
      try {
        await sendZipFile(response, employeePackage.zipPath, `Iseca-${generatedEmployee.label}.zip`);
        packageDelivered = true;
        diagnostykaStore.zapiszZdarzenie("paczka-pracownika");
      } finally {
        await employeePackage.cleanup();
      }
    } catch (error) {
      console.error(`Budowanie bazy pracownika nie powiodło się: ${error?.message || error}`);
      
      if (generatedEmployee && !packageDelivered) {
        await kontoStore.removeMember(generatedEmployee.id).catch(() => {});
      }
      if (!response.headersSent) {
        sendJson(response, 400, { error: error?.message || "Nie udało się przygotować bazy pracownika." });
      } else {
        response.destroy();
      }
    }
    return true;
  }

  const employeeAssignmentExportMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/konto\/przydzialy-polis\/([A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4})$/);
  if (employeeAssignmentExportMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    let employeeAssignmentPackage = null;
    try {
      const payload = await readJsonBody(request, { limit: MAX_SEED_REQUEST_BODY });
      const keys = payload && typeof payload === "object" && !Array.isArray(payload)
        ? Object.keys(payload)
        : [];
      if (
        keys.length !== 1
        || keys[0] !== "databaseContents"
        || typeof payload.databaseContents !== "string"
      ) {
        throw new PackageValidationError("PACKAGE_DATABASE_INVALID");
      }
      const snapshot = await kontoStore.getSnapshot();
      const sourceAccountId = normalizeAccountId(snapshot.account?.id);
      const targetAccountId = normalizeAccountId(employeeAssignmentExportMatch[1]);
      if (
        snapshot.account?.mode !== "main"
        || !sourceAccountId
        || !targetAccountId
        || !snapshot.members.some((member) => member.id === targetAccountId)
      ) {
        throw new PackageValidationError("PACKAGE_ACCOUNT_MISMATCH", { statusCode: 403 });
      }
      const credentials = await kontoStore.getMemberTransferCredentials(targetAccountId);
      if (!credentials) {
        throw new PackageValidationError("PACKAGE_PAIRING_REQUIRED", { statusCode: 403 });
      }
      employeeAssignmentPackage = await buildEmployeeAssignmentPackage({
        rootDirectory: ROOT_DIRECTORY,
        databaseContents: payload.databaseContents,
        sourceAccountId,
        targetAccountId,
        transferKey: credentials.transferKey,
        keyId: credentials.keyId,
      });
      await sendZipFile(
        response,
        employeeAssignmentPackage.zipPath,
        `Polisy-dla-pracownika-${new Date().toISOString().slice(0, 10)}.zip`,
      );
      diagnostykaStore.zapiszZdarzenie("przydzial-polis-eksport", {
        polis: employeeAssignmentPackage.policyCount,
      });
    } catch (error) {
      if (!response.headersSent) {
        sendEmployeeAssignmentError(response, error, {
          fallback: "Nie udało się bezpiecznie przygotować paczki polis.",
        });
      } else {
        response.destroy();
      }
    } finally {
      await employeeAssignmentPackage?.cleanup().catch(() => {});
    }
    return true;
  }

  
  
  if (request.method === "POST" && url.pathname === "/api/konto/paczka-centrali") {
    if (!isTrustedBinaryUpload(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const databaseContents = await readLargeRequestBody(request, 256 * 1024 * 1024);
      
      
      const filteredScope = url.searchParams.get("zakres") === "wybrane";
      const snapshot = await kontoStore.getSnapshot();
      const centralPackage = await buildCentralPackage({
        rootDirectory: ROOT_DIRECTORY,
        filesDirectory: FILES_DIRECTORY,
        databaseContents,
      });
      try {
        
        
        await kontoStore.markCentralExport({
          policyCount: centralPackage.policyCount,
          filtered: filteredScope,
        }).catch(() => {
          console.error("Nie udało się zapisać daty eksportu paczki.");
        });
        await sendZipFile(
          response,
          centralPackage.zipPath,
          `Baza-${snapshot.account?.name || "Iseca"}.zip`,
        );
        diagnostykaStore.zapiszZdarzenie("paczka-centrali", {
          polis: centralPackage.policyCount,
          zakres: filteredScope ? "wybrane" : "wszystko",
        });
      } finally {
        await centralPackage.cleanup();
      }
    } catch {
      console.error("Budowanie paczki dla centrali nie powiodło się (PACKAGE_BUILD_FAILED).");
      if (!response.headersSent) {
        sendJson(response, 400, { error: "Nie udało się bezpiecznie przygotować paczki." });
      } else {
        response.destroy();
      }
    }
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/konto/import-paczki/pending") {
    try {
      const snapshot = await kontoStore.getSnapshot();
      const centralAccountId = normalizeAccountId(snapshot.account?.id);
      if (!centralAccountId) {
        throw new PackageImportTransactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      const pending = await employeePackageImportTransactionStore.getPending({
        centralAccountId,
      });
      sendJson(response, 200, { transactions: pending });
    } catch (error) {
      sendPackageImportError(response, error);
    }
    return true;
  }

  const packageImportActionMatch = request.method === "POST"
    && url.pathname.match(
      /^\/api\/konto\/import-paczki\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\/(apply|confirm|rollback)$/,
    );
  if (packageImportActionMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const actionBinding = await readPackageImportActionBody(request);
      const snapshot = await kontoStore.getSnapshot();
      const centralAccountId = normalizeAccountId(snapshot.account?.id);
      if (!centralAccountId) {
        throw new PackageImportTransactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      const [, transactionId, action] = packageImportActionMatch;
      const result = await employeePackageImportTransactionStore[action]({
        transactionId,
        centralAccountId,
        ...actionBinding,
      });
      if (action === "apply") {
        diagnostykaStore.zapiszZdarzenie("import-bazy-pracownika-pliki", {
          zalacznikiSkopiowane: result.attachmentsCopied,
          zalacznikiPonownieUzyte: result.attachmentsReused,
          zalacznikiPrzemianowane: result.attachmentsRenamed,
        });
      }
      sendJson(
        response,
        200,
        action === "confirm" || action === "rollback"
          ? { ok: true, ...result }
          : result,
      );
    } catch (error) {
      sendPackageImportError(response, error);
    }
    return true;
  }

  
  
  if (request.method === "POST" && url.pathname === "/api/konto/import-paczki") {
    if (!isTrustedBinaryUpload(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    const expectedAccountId = normalizeAccountId(url.searchParams.get("pracownik"));
    const baseDigest = String(url.searchParams.get("bazaRewizja") || "");
    const snapshot = await kontoStore.getSnapshot();
    const centralAccountId = normalizeAccountId(snapshot.account?.id);
    if (!expectedAccountId || !/^[a-f0-9]{64}$/.test(baseDigest)) {
      sendPackageImportError(
        response,
        new PackageImportTransactionError("PACKAGE_IMPORT_INVALID"),
      );
      return true;
    }
    if (!centralAccountId) {
      sendPackageImportError(
        response,
        new PackageImportTransactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 }),
      );
      return true;
    }
    if (!snapshot.members.some((member) => member.id === expectedAccountId)) {
      sendJson(response, 403, { error: "Ten identyfikator nie jest dodany do Twojej agencji." });
      return true;
    }
    let workDirectory = "";
    try {
      await mkdir(join(FILES_DIRECTORY, "tmp"), { recursive: true });
      
      
      workDirectory = await mkdtemp(join(FILES_DIRECTORY, "tmp", "imp-"));
      const zipPath = join(workDirectory, "p.zip");
      await readRequestBodyToFile(request, zipPath, PACKAGE_MAX_UPLOAD_BYTES);
      const extractDirectory = join(workDirectory, "z");
      const packagePreflight = await preflightCentralPackageArchive({
        zipPath,
        extractionDirectory: extractDirectory,
      });
      try {
        await expandZipArchive(zipPath, extractDirectory);
      } catch {
        throw new PackageValidationError("PACKAGE_ARCHIVE_INVALID");
      }
      const validatedPackage = await validateExtractedCentralPackage({
        extractionDirectory: extractDirectory,
        preflight: packagePreflight,
        expectedAccountId,
      });
      const stagedTransaction = await employeePackageImportTransactionStore.stage({
        centralAccountId,
        sourceAccountId: validatedPackage.accountId,
        baseDigest,
        sourcePackageRoot: validatedPackage.packageRoot,
        manifest: validatedPackage.manifest,
        database: validatedPackage.database,
      });
      diagnostykaStore.zapiszZdarzenie("import-bazy-pracownika-staged", {
        polisWPaczce: stagedTransaction.policies.length,
        zalacznikiDoUtworzenia: stagedTransaction.attachmentsToCreate,
        zalacznikiPonownieUzyte: stagedTransaction.attachmentsToReuse,
        zalacznikiDoPrzemianowania: stagedTransaction.attachmentsToRename,
      });
      sendJson(response, 200, stagedTransaction);
    } catch (error) {
      sendPackageImportError(response, error);
    } finally {
      if (workDirectory) await rm(workDirectory, { recursive: true, force: true }).catch(() => {});
    }
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/konto/import-przydzialu/pending") {
    try {
      const snapshot = await kontoStore.getSnapshot();
      const targetAccountId = normalizeAccountId(snapshot.account?.id);
      if (snapshot.account?.mode !== "employee" || !targetAccountId) {
        throw new PackageImportTransactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      const credentials = await kontoStore.getEmployeeTransferCredentials();
      if (!credentials) {
        throw new PackageValidationError("PACKAGE_PAIRING_REQUIRED", { statusCode: 403 });
      }
      const pending = await employeeAssignmentImportTransactionStore.getPending({
        targetAccountId,
      });
      if (pending.some((transaction) => transaction.sourceAccountId !== credentials.centralAccountId)) {
        throw new PackageImportTransactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      sendJson(response, 200, { transactions: pending });
    } catch (error) {
      sendEmployeeAssignmentError(response, error);
    }
    return true;
  }

  const employeeAssignmentActionMatch = request.method === "POST"
    && url.pathname.match(
      /^\/api\/konto\/import-przydzialu\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\/(apply|confirm|rollback)$/,
    );
  if (employeeAssignmentActionMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const actionBinding = await readPackageImportActionBody(request);
      const snapshot = await kontoStore.getSnapshot();
      const targetAccountId = normalizeAccountId(snapshot.account?.id);
      if (snapshot.account?.mode !== "employee" || !targetAccountId) {
        throw new PackageImportTransactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      const credentials = await kontoStore.getEmployeeTransferCredentials();
      if (!credentials) {
        throw new PackageValidationError("PACKAGE_PAIRING_REQUIRED", { statusCode: 403 });
      }
      const [, transactionId, action] = employeeAssignmentActionMatch;
      const pending = await employeeAssignmentImportTransactionStore.getPending({
        targetAccountId,
      });
      const matchingTransaction = pending.find((transaction) => transaction.transactionId === transactionId);
      if (
        matchingTransaction
        && matchingTransaction.sourceAccountId !== credentials.centralAccountId
      ) {
        throw new PackageImportTransactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      const result = await employeeAssignmentImportTransactionStore[action]({
        transactionId,
        targetAccountId,
        sourceAccountId: credentials.centralAccountId,
        ...actionBinding,
      });
      if (action === "apply") {
        diagnostykaStore.zapiszZdarzenie("import-przydzialu-pliki", {
          zalacznikiSkopiowane: result.attachmentsCopied,
          zalacznikiPonownieUzyte: result.attachmentsReused,
          zalacznikiPrzemianowane: result.attachmentsRenamed,
        });
      }
      sendJson(
        response,
        200,
        action === "confirm" || action === "rollback"
          ? { ok: true, ...result }
          : result,
      );
    } catch (error) {
      sendEmployeeAssignmentError(response, error);
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/konto/import-przydzialu") {
    if (!isTrustedBinaryUpload(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    const baseDigest = String(url.searchParams.get("bazaRewizja") || "");
    let workDirectory = "";
    try {
      if (!/^[a-f0-9]{64}$/.test(baseDigest)) {
        throw new PackageImportTransactionError("PACKAGE_IMPORT_INVALID");
      }
      const snapshot = await kontoStore.getSnapshot();
      const targetAccountId = normalizeAccountId(snapshot.account?.id);
      if (snapshot.account?.mode !== "employee" || !targetAccountId) {
        throw new PackageImportTransactionError("PACKAGE_IMPORT_ACCOUNT", { statusCode: 403 });
      }
      const credentials = await kontoStore.getEmployeeTransferCredentials();
      if (!credentials) {
        throw new PackageValidationError("PACKAGE_PAIRING_REQUIRED", { statusCode: 403 });
      }
      await mkdir(join(FILES_DIRECTORY, "tmp"), { recursive: true });
      workDirectory = await mkdtemp(join(FILES_DIRECTORY, "tmp", "asg-"));
      const zipPath = join(workDirectory, "p.zip");
      await readRequestBodyToFile(request, zipPath, PACKAGE_MAX_UPLOAD_BYTES);
      const extractDirectory = join(workDirectory, "z");
      const packagePreflight = await preflightCentralPackageArchive({
        zipPath,
        extractionDirectory: extractDirectory,
      });
      try {
        await expandZipArchive(zipPath, extractDirectory);
      } catch {
        throw new PackageValidationError("PACKAGE_ARCHIVE_INVALID");
      }
      const validatedPackage = await validateExtractedEmployeeAssignmentPackage({
        extractionDirectory: extractDirectory,
        preflight: packagePreflight,
        expectedSourceAccountId: credentials.centralAccountId,
        expectedTargetAccountId: targetAccountId,
        expectedKeyId: credentials.keyId,
        transferKey: credentials.transferKey,
      });
      const stagedTransaction = await employeeAssignmentImportTransactionStore.stage({
        sourceAccountId: validatedPackage.sourceAccountId,
        targetAccountId: validatedPackage.targetAccountId,
        baseDigest,
        sourcePackageRoot: validatedPackage.packageRoot,
        manifest: validatedPackage.manifest,
        database: validatedPackage.database,
      });
      diagnostykaStore.zapiszZdarzenie("import-przydzialu-staged", {
        polisWPaczce: stagedTransaction.policies.length,
        zalacznikiDoUtworzenia: stagedTransaction.attachmentsToCreate,
        zalacznikiPonownieUzyte: stagedTransaction.attachmentsToReuse,
        zalacznikiDoPrzemianowania: stagedTransaction.attachmentsToRename,
      });
      sendJson(response, 200, stagedTransaction);
    } catch (error) {
      sendEmployeeAssignmentError(response, error);
    } finally {
      if (workDirectory) await rm(workDirectory, { recursive: true, force: true }).catch(() => {});
    }
    return true;
  }

  const memberDeleteMatch = request.method === "DELETE" && url.pathname.match(/^\/api\/konto\/pracownicy\/([A-Z2-9-]+)$/i);
  if (memberDeleteMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await kontoStore.removeMember(normalizeAccountId(memberDeleteMatch[1]));
      sendJson(response, 200, await kontoStore.getSnapshot());
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się usunąć pracownika." });
    }
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/licencja/status") {
    sendJson(response, 200, await licencjaStore.pobierzStan());
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/licencja/program") {
    const stanLicencji = await licencjaProgramu.zapewnijStan().catch(() => null);
    sendJson(response, 200, {
      ...(opisLicencjiDlaFrontu(stanLicencji) || { stan: "brak", tylkoOdczyt: true }),
      dane: await licencjaStore.pobierzStan(),
    });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/licencja/odswiez") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await readJsonBody(request).catch(() => ({}));
    const stanLicencji = await licencjaProgramu.zapewnijStan({ wymusSprawdzenie: true }).catch(() => null);
    sendJson(response, 200, {
      ...(opisLicencjiDlaFrontu(stanLicencji) || { stan: "brak", tylkoOdczyt: true }),
      dane: await licencjaStore.pobierzStan(),
    });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/licencja/zapisz") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    let poprzednieDane = null;
    try {
      const body = await readJsonBody(request);
      poprzednieDane = await licencjaStore.pobierzDaneLogowania().catch(() => null);
      await licencjaStore.zapiszDaneLogowania({ login: body?.login, haslo: body?.haslo });
      updateService.zapomnijToken();
      await licencjaProgramu.zapomnij();
      
      
      const stanLicencji = await licencjaProgramu.zapewnijStan({ wymusSprawdzenie: true });
      if (stanLicencji.stan === "brak") {
        throw Object.assign(new Error(stanLicencji.bladSprawdzenia || "Nie udało się potwierdzić licencji."), {
          code: stanLicencji.powodBledu || "LOGOWANIE_WYMAGANE",
          licencja: true,
        });
      }
      
      
      void zdeponujKluczRatunkowyJesliTrzeba({ cisza: true });
      sendJson(response, 200, {
        ...await licencjaStore.pobierzStan(),
        licencjaProgramu: opisLicencjiDlaFrontu(stanLicencji),
      });
    } catch (error) {
      
      if (error?.code === "ZLE_DANE" || error?.code === "LOGOWANIE_WYMAGANE") {
        if (poprzednieDane) {
          await licencjaStore.zapiszDaneLogowania(poprzednieDane).catch(() => {});
        } else {
          await licencjaStore.usunDaneLogowania().catch(() => {});
        }
        updateService.zapomnijToken();
      }
      if (!isLicencjaError(error)) {
        console.error(`Zapis danych licencji nie powiódł się: ${error?.message || error}`);
      }
      sendJson(response, isLicencjaError(error) ? 400 : 502, {
        error: error?.message || "Nie udało się zapisać danych logowania.",
        powod: error?.code || "",
        stan: await licencjaStore.pobierzStan(),
      });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/licencja/usun") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await readJsonBody(request).catch(() => ({}));
    await licencjaStore.usunDaneLogowania();
    updateService.zapomnijToken();
    await licencjaProgramu.zapomnij();
    sendJson(response, 200, await licencjaStore.pobierzStan());
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/update/status") {
    try {
      sendJson(response, 200, await updateService.checkForUpdate());
    } catch (error) {
      console.error(`Sprawdzanie aktualizacji nie powiodło się: ${error?.message || error}`);
      sendJson(response, 502, { error: error?.message || "Nie udało się sprawdzić dostępności aktualizacji." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/update/prepare") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await readJsonBody(request);
      sendJson(response, 200, await updateService.prepareUpdate());
    } catch (error) {
      
      
      if (!isLicencjaError(error)) {
        console.error(`Pobieranie aktualizacji nie powiodło się: ${error?.message || error}`);
      }
      sendJson(response, isLicencjaError(error) ? 403 : 502, {
        error: error?.message || "Nie udało się pobrać aktualizacji.",
        powod: error?.code || "",
        licencja: await licencjaStore.pobierzStan().catch(() => null),
      });
    }
    return true;
  }

  if (request.method === "GET" && url.pathname === "/api/automation/status") {
    const [wartaRoute, generaliRoute, mtuRoute, mtuPortfolioRoute, trastiRoute, wienerRoute, compensaRoute] = await Promise.all([
      routeStore.loadRoute("warta"),
      routeStore.loadRoute("generali"),
      routeStore.loadRoute("mtu"),
      routeStore.loadRoute("mtu-portfel").catch(() => null),
      routeStore.loadRoute("trasti"),
      routeStore.loadRoute("wiener"),
      routeStore.loadRoute("compensa"),
    ]);
    
    
    
    const [
      wartaPasswordSaved,
      generaliPasswordSaved,
      mtuPasswordSaved,
      hestiaPasswordSaved,
      trastiPasswordSaved,
      wienerPasswordSaved,
      compensaPasswordSaved,
      allianzPasswordSaved,
      inslyPasswordSaved,
      pzuPasswordSaved,
    ] = await Promise.all([
      credentialVault.hasWartaPassword(),
      credentialVault.hasGeneraliPassword(),
      credentialVault.hasMtuPassword(),
      credentialVault.hasHestiaPassword(),
      credentialVault.hasTrastiPassword(),
      credentialVault.hasWienerPassword(),
      credentialVault.hasCompensaPassword(),
      credentialVault.hasAllianzPassword(),
      credentialVault.hasInslyPassword(),
      credentialVault.hasPzuPassword(),
    ]);
    sendJson(response, 200, {
      available: Boolean(chromeExecutablePath),
      browser: chromeExecutablePath ? "Google Chrome" : "",
      credentials: {
        wartaPasswordSaved,
        wartaPathSaved: Boolean(wartaRoute && wartaPathIncludesRecordSelection(wartaRoute.formPath)),
        wartaRouteSteps: wartaRoute && wartaPathIncludesRecordSelection(wartaRoute.formPath)
          ? { form: wartaRoute.formPath.length, results: wartaRoute.resultPath.length }
          : { form: 0, results: 0 },
        generaliPasswordSaved,
        generaliPathSaved: Boolean(generaliRoute),
        generaliRouteSteps: generaliRoute
          ? { form: generaliRoute.formPath.length, results: generaliRoute.resultPath.length }
          : { form: 0, results: 0 },
        mtuPasswordSaved,
        mtuPathSaved: Boolean(mtuRoute),
        mtuRouteSteps: mtuRoute
          ? { form: mtuRoute.formPath.length, results: mtuRoute.resultPath.length }
          : { form: 0, results: 0 },
        mtuPortfolioPathSaved: Boolean(mtuPortfolioRoute && mtuPortfolioRoute.formPath.length > 0),
        mtuPortfolioRouteSteps: mtuPortfolioRoute
          ? { form: mtuPortfolioRoute.formPath.length, results: 0 }
          : { form: 0, results: 0 },
        hestiaPasswordSaved,
        trastiPasswordSaved,
        trastiPathSaved: Boolean(trastiRoute),
        trastiRouteSteps: trastiRoute
          ? { form: trastiRoute.formPath.length, results: trastiRoute.resultPath.length }
          : { form: 0, results: 0 },
        wienerPasswordSaved,
        wienerPathSaved: Boolean(wienerRoute),
        wienerRouteSteps: wienerRoute
          ? { form: wienerRoute.formPath.length, results: wienerRoute.resultPath.length }
          : { form: 0, results: 0 },
        compensaPasswordSaved,
        compensaPathSaved: Boolean(compensaRoute),
        compensaRouteSteps: compensaRoute
          ? { form: compensaRoute.formPath.length, results: compensaRoute.resultPath.length }
          : { form: 0, results: 0 },
        allianzPasswordSaved,
        inslyPasswordSaved,
        pzuPasswordSaved,
      },
      message: chromeExecutablePath
        ? "Puppeteer jest gotowy do uruchomienia Google Chrome."
        : "Nie znaleziono instalacji Google Chrome.",
    });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/warta") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      if (!password) throw new Error("Hasło do Warty nie może być puste.");
      await credentialVault.saveWartaPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się bezpiecznie zapisać hasła." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/warta") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteWartaPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/insly") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      if (!password) throw new Error("Hasło do Superpolisy nie może być puste.");
      await credentialVault.saveInslyPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się bezpiecznie zapisać hasła." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/insly") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteInslyPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/pzu") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      if (!password) throw new Error("Hasło do PZU nie może być puste.");
      await credentialVault.savePzuPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się bezpiecznie zapisać hasła." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/pzu") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deletePzuPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/generali") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      if (!password) throw new Error("Hasło do Generali nie może być puste.");
      await credentialVault.saveGeneraliPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się bezpiecznie zapisać hasła." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/generali") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteGeneraliPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/mtu") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      const username = typeof payload?.username === "string" ? payload.username.trim().slice(0, 120) : "";
      if (!password) throw new Error("Hasło do MTU nie może być puste.");
      if (username) validateMtuCredentials(username, password);
      await credentialVault.saveMtuPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się bezpiecznie zapisać hasła MTU." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/mtu") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteMtuPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/hestia") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      const username = typeof payload?.username === "string" ? payload.username.trim().slice(0, 120) : "";
      if (!password) throw new Error("Hasło do Ergo Hestii nie może być puste.");
      if (username) validateHestiaCredentials(username, password);
      await credentialVault.saveHestiaPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się bezpiecznie zapisać hasła Ergo Hestii." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/hestia") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteHestiaPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/trasti") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      if (!password) throw new Error("Hasło do Trasti nie może być puste.");
      await credentialVault.saveTrastiPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się bezpiecznie zapisać hasła Trasti." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/trasti") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteTrastiPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/wiener") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      if (!password) throw new Error("Hasło do Wiener nie może być puste.");
      await credentialVault.saveWienerPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się bezpiecznie zapisać hasła Wiener." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/wiener") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteWienerPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/compensa") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "\u017b\u0105danie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      if (!password) throw new Error("Has\u0142o do Compensy nie mo\u017ce by\u0107 puste.");
      await credentialVault.saveCompensaPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie uda\u0142o si\u0119 bezpiecznie zapisa\u0107 has\u0142a Compensa." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/compensa") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "\u017b\u0105danie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteCompensaPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/credentials/allianz") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "\u017b\u0105danie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const password = typeof payload?.password === "string" ? payload.password.slice(0, 256) : "";
      if (!password) throw new Error("Has\u0142o do Allianz nie mo\u017ce by\u0107 puste.");
      await credentialVault.saveAllianzPassword(password);
      sendJson(response, 200, { saved: true });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie uda\u0142o si\u0119 bezpiecznie zapisa\u0107 has\u0142a Allianz." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/allianz") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "\u017b\u0105danie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await credentialVault.deleteAllianzPassword();
    sendJson(response, 200, { saved: false });
    return true;
  }

  const routeRestoreMatch = url.pathname.match(/^\/api\/automation\/routes\/(warta|generali|mtu|trasti|wiener|compensa)\/restore$/);
  if (request.method === "POST" && routeRestoreMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const restored = await routeStore.restoreRoute(routeRestoreMatch[1]);
      sendJson(response, 200, {
        restored: true,
        source: restored.source,
        steps: {
          form: restored.route.formPath.length,
          results: restored.route.resultPath.length,
        },
      });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się przywrócić trasy." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/warta/path") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await routeStore.deleteRoute("warta");
      sendJson(response, 200, { saved: false });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się usunąć zapamiętanej trasy Warty." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/generali/path") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await routeStore.deleteRoute("generali");
      sendJson(response, 200, { saved: false });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się usunąć zapamiętanej trasy Generali." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/mtu/path") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await routeStore.deleteRoute("mtu");
      sendJson(response, 200, { saved: false });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się usunąć zapamiętanej trasy MTU." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/trasti/path") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await routeStore.deleteRoute("trasti");
      sendJson(response, 200, { saved: false });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się usunąć zapamiętanej trasy Trasti." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/wiener/path") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await routeStore.deleteRoute("wiener");
      sendJson(response, 200, { saved: false });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się usunąć zapamiętanej trasy Wiener." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/automation/routes/warta") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const route = payload?.route;
      if (route?.version !== 1 || route?.insurer !== "warta" || !Array.isArray(route?.formPath) || !Array.isArray(route?.resultPath)) {
        throw new Error("Wybrany plik nie jest prawidłową trasą Warty.");
      }
      if (!wartaPathIncludesRecordSelection(route.formPath)) {
        throw new Error("Ta trasa Warty nie zawiera wyboru rekordu. Nagraj ją ponownie od ekranu po logowaniu.");
      }
      const savedRoute = await routeStore.saveRoute("warta", route);
      sendJson(response, 200, {
        saved: true,
        steps: { form: savedRoute.formPath.length, results: savedRoute.resultPath.length },
      });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się wczytać trasy Warty." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/automation/routes/generali") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const route = payload?.route;
      if (route?.version !== 1 || route?.insurer !== "generali" || !Array.isArray(route?.formPath) || !Array.isArray(route?.resultPath)) {
        throw new Error("Wybrany plik nie jest prawidłową trasą Generali.");
      }
      const savedRoute = await routeStore.saveRoute("generali", route);
      sendJson(response, 200, {
        saved: true,
        steps: { form: savedRoute.formPath.length, results: savedRoute.resultPath.length },
      });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się wczytać trasy Generali." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/automation/routes/mtu") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const route = payload?.route;
      if (route?.version !== 1 || route?.insurer !== "mtu" || !Array.isArray(route?.formPath) || !Array.isArray(route?.resultPath)) {
        throw new Error("Wybrany plik nie jest prawidłową trasą MTU.");
      }
      const savedRoute = await routeStore.saveRoute("mtu", route);
      sendJson(response, 200, {
        saved: true,
        steps: { form: savedRoute.formPath.length, results: savedRoute.resultPath.length },
      });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się wczytać trasy MTU." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/automation/routes/trasti") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const route = payload?.route;
      if (route?.version !== 1 || route?.insurer !== "trasti" || !Array.isArray(route?.formPath) || !Array.isArray(route?.resultPath)) {
        throw new Error("Wybrany plik nie jest prawidłową trasą Trasti.");
      }
      const savedRoute = await routeStore.saveRoute("trasti", route);
      sendJson(response, 200, {
        saved: true,
        steps: { form: savedRoute.formPath.length, results: savedRoute.resultPath.length },
      });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się wczytać trasy Trasti." });
    }
    return true;
  }

  if (request.method === "DELETE" && url.pathname === "/api/credentials/compensa/path") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "\u017b\u0105danie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      await routeStore.deleteRoute("compensa");
      sendJson(response, 200, { saved: false });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie uda\u0142o si\u0119 usun\u0105\u0107 zapami\u0119tanej trasy Compensa." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/automation/routes/compensa") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "\u017b\u0105danie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const route = payload?.route;
      if (route?.version !== 1 || route?.insurer !== "compensa" || !Array.isArray(route?.formPath) || !Array.isArray(route?.resultPath)) {
        throw new Error("Wybrany plik nie jest prawid\u0142ow\u0105 tras\u0105 Compensa.");
      }
      const savedRoute = await routeStore.saveRoute("compensa", route);
      sendJson(response, 200, {
        saved: true,
        steps: { form: savedRoute.formPath.length, results: savedRoute.resultPath.length },
      });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie uda\u0142o si\u0119 wczyta\u0107 trasy Compensa." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/automation/routes/wiener") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const route = payload?.route;
      if (route?.version !== 1 || route?.insurer !== "wiener" || !Array.isArray(route?.formPath) || !Array.isArray(route?.resultPath)) {
        throw new Error("Wybrany plik nie jest prawidłową trasą Wiener.");
      }
      const savedRoute = await routeStore.saveRoute("wiener", route);
      sendJson(response, 200, {
        saved: true,
        steps: { form: savedRoute.formPath.length, results: savedRoute.resultPath.length },
      });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się wczytać trasy Wiener." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/warta/quotes") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const credentials = validateQuotePayload(await readJsonBody(request), "Warty");
      credentials.password ||= await credentialVault.loadWartaPassword();
      if (!credentials.password) throw new Error("Brakuje zapisanego hasła do Warty.");
      const job = {
        id: randomUUID(),
        insurer: "Warta",
        kind: "quote",
        status: "queued",
        title: "Kalkulacja oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "warta",
        clientBatchId: credentials.clientBatchId,
        manualMode: credentials.manualMode === true,
        request: { registration: credentials.registration, pesel: credentials.pesel, vin: credentials.vin, username: credentials.username, vehicleInfo: credentials.vehicleInfo },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      registerQuoteJob(job, () => enqueueWartaJob(job, credentials));
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć kalkulacji." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/generali/quotes") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const credentials = validateQuotePayload(await readJsonBody(request), "Generali");
      credentials.password ||= await credentialVault.loadGeneraliPassword();
      if (!credentials.password) throw new Error("Brakuje zapisanego hasła do Generali.");
      const job = {
        id: randomUUID(),
        insurer: "Generali",
        kind: "quote",
        status: "queued",
        title: "Kalkulacja oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "generali",
        clientBatchId: credentials.clientBatchId,
        manualMode: credentials.manualMode === true,
        request: { registration: credentials.registration, pesel: credentials.pesel, vin: credentials.vin, username: credentials.username, vehicleInfo: credentials.vehicleInfo },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      registerQuoteJob(job, () => enqueueGeneraliJob(job, credentials));
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć kalkulacji Generali." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/mtu/quotes") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const credentials = validateQuotePayload(await readJsonBody(request), "MTU");
      credentials.password ||= await credentialVault.loadMtuPassword();
      validateMtuCredentials(credentials.username, credentials.password);
      const job = {
        id: randomUUID(),
        insurer: "MTU",
        kind: "quote",
        status: "queued",
        title: "Kalkulacja oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "mtu",
        clientBatchId: credentials.clientBatchId,
        manualMode: credentials.manualMode === true,
        request: { registration: credentials.registration, pesel: credentials.pesel, vin: credentials.vin, username: credentials.username, vehicleInfo: credentials.vehicleInfo },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      registerQuoteJob(job, () => enqueueMtuJob(job, credentials));
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć kalkulacji MTU." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/mtu/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const username = String(payload?.username || "").trim().slice(0, 120);
      if (!username) throw new Error("Brakuje loginu do MTU.");
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadMtuPassword();
      validateMtuCredentials(username, password);
      const credentials = { username, password };
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "mtu",
        5_000,
      );
      const knownPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.knownPolicyNumbers,
        "mtu",
        10_000,
      );
      
      
      const pdfBacklogOnly = payload?.pdfBacklogOnly === true && payload?.downloadPdfs === true;
      const pdfBacklogPolicyNumbers = pdfBacklogOnly
        ? normalizePortfolioPdfIdentityList(
          payload?.pdfBacklogPolicyNumbers,
          "mtu",
          10_000,
        )
        : [];
      if (pdfBacklogOnly && pdfBacklogPolicyNumbers.length === 0) {
        throw new Error("Brak zaległych dokumentów do pobrania.");
      }
      const job = {
        id: randomUUID(),
        insurer: "MTU",
        kind: "portfolio",
        status: "queued",
        title: "Import polis oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        knownPolicyNumbers,
        pdfBacklogOnly,
        pdfBacklogPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true && !pdfBacklogOnly,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "mtu",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueMtuPortfolioJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć importu polis MTU." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/hestia/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const username = String(payload?.username || "").trim().slice(0, 120);
      if (!username) throw new Error("Brakuje loginu do Ergo Hestii.");
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadHestiaPassword();
      validateHestiaCredentials(username, password);
      const credentials = { username, password };
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "hestia",
        5_000,
      );
      const knownPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.knownPolicyNumbers,
        "hestia",
        10_000,
      );
      
      
      const pdfBacklogOnly = payload?.pdfBacklogOnly === true && payload?.downloadPdfs === true;
      const pdfBacklogPolicyNumbers = pdfBacklogOnly
        ? normalizePortfolioPdfIdentityList(
          payload?.pdfBacklogPolicyNumbers,
          "hestia",
          10_000,
        )
        : [];
      if (pdfBacklogOnly && pdfBacklogPolicyNumbers.length === 0) {
        throw new Error("Brak zaległych dokumentów do pobrania.");
      }
      const job = {
        id: randomUUID(),
        insurer: "Ergo Hestia",
        kind: "portfolio",
        status: "queued",
        title: "Import polis oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        knownPolicyNumbers,
        pdfBacklogOnly,
        pdfBacklogPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true && !pdfBacklogOnly,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "hestia",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueHestiaPortfolioJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć importu polis Ergo Hestii." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/wiener/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const username = String(payload?.username || "").trim().slice(0, 120);
      if (!username) throw new Error("Brakuje loginu do Wiener.");
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadWienerPassword();
      if (!password) throw new Error("Brakuje zapisanego hasła do Wiener.");
      const credentials = { username, password };
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "wiener",
        5_000,
      );
      const knownPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.knownPolicyNumbers,
        "wiener",
        10_000,
      );
      const job = {
        id: randomUUID(),
        insurer: "Wiener",
        kind: "portfolio",
        status: "queued",
        title: "Import polis oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        knownPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "wiener",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueWienerPortfolioJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć importu polis Wiener." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/generali/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const username = String(payload?.username || "").trim().slice(0, 120);
      if (!username) throw new Error("Brakuje loginu do Generali.");
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadGeneraliPassword();
      if (!password) throw new Error("Brakuje zapisanego hasła do Generali.");
      const credentials = { username, password };
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "generali",
        5_000,
      );
      const knownPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.knownPolicyNumbers,
        "generali",
        10_000,
      );
      const job = {
        id: randomUUID(),
        insurer: "Generali",
        kind: "portfolio",
        status: "queued",
        title: "Import polis oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        knownPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "generali",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueGeneraliPortfolioJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć importu polis Generali." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/warta/portfolio/records") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const username = String(payload?.username || "").trim().slice(0, 120);
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadWartaPassword();
      if (!username) throw new Error("Brakuje loginu do Warty.");
      if (!password) throw new Error("Brakuje zapisanego hasła do Warty.");
      const credentials = { username, password };
      const job = {
        id: randomUUID(),
        insurer: "Warta",
        kind: "portfolio-records",
        status: "queued",
        title: "Pobranie listy rekordów Warty oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        records: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "warta",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueWartaPortfolioRecordsJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się pobrać listy rekordów Warty." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/warta/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const username = String(payload?.username || "").trim().slice(0, 120);
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadWartaPassword();
      if (!username) throw new Error("Brakuje loginu do Warty.");
      if (!password) throw new Error("Brakuje zapisanego hasła do Warty.");
      const agreementId = String(payload?.agreementId || "").trim().slice(0, 40);
      if (!agreementId) throw new Error("Nie wybrano rekordu Warty do importu.");
      const agreementLabel = String(payload?.agreementLabel || "").replace(/\s+/g, " ").trim().slice(0, 200);
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "warta",
        5_000,
      );
      const knownPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.knownPolicyNumbers,
        "warta",
        10_000,
      );
      const credentials = { username, password };
      const job = {
        id: randomUUID(),
        insurer: "Warta",
        kind: "portfolio",
        status: "queued",
        title: "Import polis Warty oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        records: [],
        agreementId,
        agreementLabel,
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        knownPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "warta",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueWartaPortfolioJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć importu polis Warty." });
    }
    return true;
  }

  
  
  if (request.method === "POST" && url.pathname === "/api/pzu/portfolio/open") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const openPayload = await readJsonBody(request).catch(() => ({}));
      const pzuOpenCredentials = {
        username: String(openPayload?.username || "").trim().slice(0, 120),
        password: await credentialVault.loadPzuPassword().catch(() => ""),
      };
      const job = {
        id: randomUUID(),
        insurer: "PZU",
        kind: "portfolio-open",
        status: "queued",
        title: "Otwarcie okna PZU oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        records: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "pzu",
        request: {},
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueuePzuOpenJob(job, pzuOpenCredentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się otworzyć okna PZU." });
    }
    return true;
  }

  
  
  
  if (request.method === "POST" && url.pathname === "/api/pzu/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const pzuCredentials = {
        username: String(payload?.username || "").trim().slice(0, 120),
        password: await credentialVault.loadPzuPassword().catch(() => ""),
      };
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "pzu",
        5_000,
      );
      const knownPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.knownPolicyNumbers,
        "pzu",
        10_000,
      );
      const job = {
        id: randomUUID(),
        insurer: "PZU",
        kind: "portfolio",
        status: "queued",
        title: "Import polis PZU oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        records: [],
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        knownPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "pzu",
        request: {},
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueuePzuPortfolioJob(job, pzuCredentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć importu polis PZU." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/insly/portfolio/open") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      
      const username = String(payload?.username || "").trim().slice(0, 120);
      const password = String(payload?.password || "").slice(0, 256)
        || await credentialVault.loadInslyPassword().catch(() => "");
      const job = {
        id: randomUUID(),
        insurer: "Superpolisa",
        kind: "portfolio-open",
        status: "queued",
        title: "Otwarcie okna Superpolisy oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        records: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "insly",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueInslyOpenJob(job, { username, password });
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się otworzyć okna Superpolisy." });
    }
    return true;
  }

  
  
  
  if (request.method === "POST" && url.pathname === "/api/insly/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      
      const username = String(payload?.username || "").trim().slice(0, 120);
      const password = String(payload?.password || "").slice(0, 256)
        || await credentialVault.loadInslyPassword().catch(() => "");
      const skipPdfPolicyKeys = sanitizeInslyPdfPolicyKeys(payload?.skipPdfPolicyKeys, 5000);
      const knownPdfPolicyKeys = sanitizeInslyPdfPolicyKeys(payload?.knownPdfPolicyKeys, 10000);
      const existingInslyImport = [...jobs.values()].find((candidate) => (
        candidate.insurerId === "insly"
        && candidate.kind === "portfolio"
        && (
          RUNNING_PORTFOLIO_JOB_STATUSES.has(candidate.status)
          || candidate.status === "completed"
        )
      ));
      if (existingInslyImport) {
        const conflict = new Error("Import z Superpolisy już trwa albo czeka na zapis. Dokończ go przed uruchomieniem następnego.");
        conflict.statusCode = 409;
        throw conflict;
      }
      const job = {
        id: randomUUID(),
        insurer: "Superpolisa",
        kind: "portfolio",
        status: "queued",
        title: "Import polis z Superpolisy oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        records: [],
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyKeys,
        knownPdfPolicyKeys,
        forceFullReimport: payload?.fullReimport === true,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "insly",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueInslyPortfolioJob(job, { username, password });
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, Number(error?.statusCode) || 400, { error: error?.message || "Nie udało się rozpocząć importu polis z Superpolisy." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/trasti/quotes") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const credentials = validateQuotePayload(await readJsonBody(request), "Trasti");
      credentials.password ||= await credentialVault.loadTrastiPassword();
      if (!credentials.password) throw new Error("Brakuje zapisanego hasła do Trasti.");
      const job = {
        id: randomUUID(),
        insurer: "Trasti",
        kind: "quote",
        status: "queued",
        title: "Kalkulacja oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "trasti",
        clientBatchId: credentials.clientBatchId,
        manualMode: credentials.manualMode === true,
        request: { registration: credentials.registration, pesel: credentials.pesel, vin: credentials.vin, username: credentials.username, vehicleInfo: credentials.vehicleInfo },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      registerQuoteJob(job, () => enqueueTrastiJob(job, credentials));
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć kalkulacji Trasti." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/trasti/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const username = String(payload?.username || "").trim().slice(0, 120);
      if (!username) throw new Error("Brakuje adresu e-mail do Trasti.");
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadTrastiPassword();
      if (!password) throw new Error("Brakuje zapisanego hasła do Trasti.");
      const credentials = { username, password };
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "trasti",
        5_000,
      );
      const knownPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.knownPolicyNumbers,
        "trasti",
        10_000,
      );
      const job = {
        id: randomUUID(),
        insurer: "Trasti",
        kind: "portfolio",
        status: "queued",
        title: "Import polis oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        knownPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "trasti",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueTrastiPortfolioJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć importu polis Trasti." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/wiener/quotes") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const credentials = validateQuotePayload(await readJsonBody(request), "Wiener");
      credentials.password ||= await credentialVault.loadWienerPassword();
      if (!credentials.password) throw new Error("Brakuje zapisanego hasła do Wiener.");
      const job = {
        id: randomUUID(),
        insurer: "Wiener",
        kind: "quote",
        status: "queued",
        title: "Kalkulacja oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "wiener",
        clientBatchId: credentials.clientBatchId,
        manualMode: credentials.manualMode === true,
        request: { registration: credentials.registration, pesel: credentials.pesel, vin: credentials.vin, username: credentials.username, vehicleInfo: credentials.vehicleInfo },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      registerQuoteJob(job, () => enqueueWienerJob(job, credentials));
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć kalkulacji Wiener." });
    }
    return true;
  }

  
  
  
  if (request.method === "POST" && url.pathname === "/api/historia-pojazdu") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    let zapytanie;
    try {
      zapytanie = walidujZapytanieHistorii(await readJsonBody(request));
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Sprawdź dane pojazdu i spróbuj ponownie." });
      return true;
    }
    try {
      const pojazd = await pobierzDaneZHistoriiPojazdu(zapytanie);
      zapiszHistoriePojazduDoMagazynu(zapytanie, pojazd);
      sendJson(response, 200, { pojazd });
    } catch (error) {
      const kod = String(error?.code ?? "");
      const status = kod === "POJAZD_NIE_ZNALEZIONY" ? 404 : kod === "LIMIT_ZAPYTAN" ? 429 : 502;
      
      
      console.error("Historia pojazdu: pobieranie nie powiodło się.", kod || error?.name || "BLAD_NIEZNANY");
      sendJson(response, status, {
        error: kod
          ? error.message
          : "Nie udało się pobrać danych z HistoriaPojazdu.gov. Spróbuj ponownie za chwilę.",
      });
    }
    return true;
  }

  
  
  
  if (request.method === "POST" && url.pathname === "/api/rejestr-firm/nip") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    let zapytanie;
    try {
      zapytanie = await readJsonBody(request, { limit: 4 * 1024 });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nieprawidłowe zapytanie." });
      return true;
    }
    try {
      const wynik = await znajdzNipPoRegonie(zapytanie?.regon);
      sendJson(response, 200, wynik);
    } catch (error) {
      const kod = String(error?.code ?? "");
      const status = kod === "ZLY_REGON" ? 400 : kod === "LIMIT_ZAPYTAN" ? 429 : 502;
      
      console.error("Rejestr firm: wyszukanie NIP-u nie powiodło się.", kod || error?.name || "BLAD_NIEZNANY");
      sendJson(response, status, {
        error: kod === "LIMIT_ZAPYTAN"
          ? "Rejestr podatników chwilowo ogranicza liczbę zapytań. Spróbuj ponownie później."
          : "Nie udało się połączyć z rejestrem podatników. Spróbuj ponownie za chwilę.",
      });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/allianz/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request);
      const username = String(payload?.username || "").trim().slice(0, 120);
      if (!username) throw new Error("Brakuje loginu do Allianz.");
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadAllianzPassword();
      if (!password) throw new Error("Brakuje zapisanego hasła do Allianz.");
      const credentials = { username, password };
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "allianz",
        5_000,
      );
      const knownPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.knownPolicyNumbers,
        "allianz",
        10_000,
      );
      const job = {
        id: randomUUID(),
        insurer: "Allianz",
        kind: "portfolio",
        status: "queued",
        title: "Import polis oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        knownPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true,
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "allianz",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueAllianzPortfolioJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć importu polis Allianz." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/compensa/portfolio") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "\u017b\u0105danie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
      const username = String(payload?.username || "").trim().slice(0, 120);
      if (!username) throw new Error("Brakuje loginu do Compensy.");
      const password = String(payload?.password || "").slice(0, 256) || await credentialVault.loadCompensaPassword();
      if (!password) throw new Error("Brakuje zapisanego has\u0142a do Compensy.");
      const credentials = { username, password };
      const skipPdfPolicyNumbers = normalizePortfolioPdfIdentityList(
        payload?.skipPdfPolicyNumbers,
        "compensa",
        5_000,
      );
      const job = {
        id: randomUUID(),
        insurer: "Compensa",
        kind: "portfolio",
        downloadPdfs: payload?.downloadPdfs === true,
        skipPdfPolicyNumbers,
        forceFullReimport: payload?.fullReimport === true,
        status: "queued",
        title: "Import polis oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        policies: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "compensa",
        request: { username },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      jobs.set(job.id, job);
      enqueueCompensaPortfolioJob(job, credentials);
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie uda\u0142o si\u0119 rozpocz\u0105\u0107 importu polis Compensa." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/allianz/quotes") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const credentials = validateQuotePayload(await readJsonBody(request), "Allianz");
      credentials.password ||= await credentialVault.loadAllianzPassword();
      if (!credentials.password) throw new Error("Brakuje zapisanego hasła do Allianz.");
      const job = {
        id: randomUUID(),
        insurer: "Allianz",
        kind: "quote",
        status: "queued",
        title: "Kalkulacja oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "allianz",
        clientBatchId: credentials.clientBatchId,
        manualMode: credentials.manualMode === true,
        request: {
          registration: credentials.registration,
          pesel: credentials.pesel,
          vin: credentials.vin,
          username: credentials.username,
          vehicleInfo: credentials.vehicleInfo,
        },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      registerQuoteJob(job, () => enqueueAllianzJob(job, credentials));
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie udało się rozpocząć kalkulacji Allianz." });
    }
    return true;
  }

  if (request.method === "POST" && url.pathname === "/api/compensa/quotes") {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "\u017b\u0105danie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    if (!chromeExecutablePath) {
      sendJson(response, 503, { error: "Nie znaleziono Google Chrome." });
      return true;
    }
    try {
      const credentials = validateQuotePayload(await readJsonBody(request), "Compensa");
      credentials.password ||= await credentialVault.loadCompensaPassword();
      if (!credentials.password) throw new Error("Brakuje zapisanego has\u0142a do Compensy.");
      const job = {
        id: randomUUID(),
        insurer: "Compensa",
        kind: "quote",
        status: "queued",
        title: "Kalkulacja oczekuje na uruchomienie",
        detail: "",
        premiums: [],
        navigationLearned: false,
        manualAvailable: false,
        insurerId: "compensa",
        clientBatchId: credentials.clientBatchId,
        manualMode: credentials.manualMode === true,
        request: { registration: credentials.registration, pesel: credentials.pesel, vin: credentials.vin, username: credentials.username, vehicleInfo: credentials.vehicleInfo },
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      registerQuoteJob(job, () => enqueueCompensaJob(job, credentials));
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, 400, { error: error?.message || "Nie uda\u0142o si\u0119 rozpocz\u0105\u0107 kalkulacji Compensa." });
    }
    return true;
  }

  const inslyPdfMatch = request.method === "GET"
    && url.pathname.match(/^\/api\/insly\/portfolio\/pdf\/([0-9A-Za-z_-]{32})$/);
  const wartaJobPdfMatch = request.method === "GET"
    && (
      url.pathname.match(/^\/api\/(warta|wiener)\/portfolio\/pdf\/([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\/([0-9A-Za-z_-]{32})$/i)
      || url.pathname.match(/^\/api\/(pzu|mtu|hestia|trasti|generali|compensa|allianz|insly)\/portfolio\/pdf\/([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\/([0-9A-Za-z_-]{32})$/i)
    );
  if (wartaJobPdfMatch) {
    const requestedInsurerId = wartaJobPdfMatch[1].toLowerCase();
    const job = jobs.get(wartaJobPdfMatch[2]);
    const pdfKey = wartaJobPdfMatch[3];
    const jobDirectory = typeof job?.pdfDirectory === "string" ? resolve(job.pdfDirectory) : "";
    const wrongInsurer = !job || job.insurerId !== requestedInsurerId;
    const keyBelongsToJob = Array.isArray(job?.policies)
      && job.policies.some((policy) => (
        policy?.pdfAvailable === true
        && policy?.pdfKey === pdfKey
      ));
    if (
      !job
      || job.kind !== "portfolio"
      || wrongInsurer
      || job.status !== "completed"
      || !keyBelongsToJob
    ) {
      sendJson(response, 404, { error: "Nie znaleziono pliku PDF polisy." });
      return true;
    }
    try {
      const validatedDirectory = await validatePortfolioPdfJobDirectory({
        filesDirectory: FILES_DIRECTORY,
        jobId: job.id,
        jobDirectory,
      });
      const contents = await readFile(join(validatedDirectory, `${pdfKey}.pdf`));
      updateJob(job, {});
      applyCommonHeaders(response);
      response.statusCode = 200;
      response.setHeader("Content-Type", "application/pdf");
      response.setHeader("Content-Length", contents.length);
      response.end(contents);
    } catch {
      sendJson(response, 404, { error: "Nie znaleziono pliku PDF polisy." });
    }
    return true;
  }
  
  
  
  if (inslyPdfMatch) {
    const pdfFileKey = inslyPdfMatch[1];
    const candidates = [...jobs.values()].filter((candidate) => (
      candidate.insurerId === "insly"
      && candidate.kind === "portfolio"
      && candidate.status === "completed"
      && typeof candidate.pdfDirectory === "string"
      && Array.isArray(candidate.policies)
      && candidate.policies.some((policy) => (
        policy?.pdfAvailable === true
        && policy?.pdfKey === pdfFileKey
      ))
    ));
    if (candidates.length !== 1) {
      sendJson(response, 404, { error: "Nie znaleziono pliku PDF polisy." });
      return true;
    }
    const job = candidates[0];
    try {
      const validatedDirectory = await validatePortfolioPdfJobDirectory({
        filesDirectory: FILES_DIRECTORY,
        jobId: job.id,
        jobDirectory: resolve(job.pdfDirectory),
      });
      const contents = await readFile(join(validatedDirectory, `${pdfFileKey}.pdf`));
      updateJob(job, {});
      applyCommonHeaders(response);
      response.statusCode = 200;
      response.setHeader("Content-Type", "application/pdf");
      response.setHeader("Content-Length", contents.length);
      response.end(contents);
    } catch {
      sendJson(response, 404, { error: "Nie znaleziono pliku PDF polisy." });
    }
    return true;
  }

  const inputJobMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/automation\/jobs\/([a-f0-9-]+)\/input$/i);
  if (inputJobMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    const payload = await readJsonBody(request);
    const job = jobs.get(inputJobMatch[1]);
    if (!job) {
      sendJson(response, 404, { error: "Nie znaleziono kalkulacji." });
      return true;
    }
    const requestId = String(payload?.requestId || "");
    if (job.status !== "input_required" || !job.pendingInput || job.pendingInput.id !== requestId) {
      sendJson(response, 409, { error: "Ta kalkulacja nie oczekuje już na uzupełnienie pól." });
      return true;
    }
    if (payload?.cancel === true) {
      job.pendingInput.finish(null);
      sendJson(response, 202, { job: getPublicJob(job) });
      return true;
    }
    const rawValues = payload?.values && typeof payload.values === "object" && !Array.isArray(payload.values)
      ? payload.values
      : {};
    const values = {};
    for (const [key, rawValue] of Object.entries(rawValues).slice(0, 40)) {
      const fieldId = String(key).slice(0, 30);
      if (!fieldId) continue;
      if (rawValue && typeof rawValue === "object") {
        values[fieldId] = {
          value: String(rawValue.value ?? "").slice(0, 300),
          checked: rawValue.checked === true,
        };
      } else {
        values[fieldId] = String(rawValue ?? "").slice(0, 300);
      }
    }
    job.pendingInput.finish(values);
    sendJson(response, 202, { job: getPublicJob(job) });
    return true;
  }

  if (
    request.method === "POST"
    && url.pathname === "/api/automation/portfolio-checkpoints/reset"
  ) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    const payload = await readJsonBody(request);
    const checkpointKey = String(payload?.checkpointKey || "").trim();
    const insurerId = checkpointKey.split(":", 1)[0].toLowerCase();
    if (!PORTFOLIO_INSURER_IDS.has(insurerId)) {
      sendJson(response, 400, { error: "Nieprawidłowy klucz checkpointu importu." });
      return true;
    }
    if (portfolioCheckpointResetsInProgress.has(insurerId)) {
      sendJson(response, 409, { error: "Zerowanie tego checkpointu już trwa." });
      return true;
    }
    portfolioCheckpointResetsInProgress.add(insurerId);
    try {
      const conflictingJob = [...jobs.values()].find((candidate) => (
        candidate.kind === "portfolio"
        && candidate.insurerId === insurerId
        && (
          RUNNING_PORTFOLIO_JOB_STATUSES.has(candidate.status)
          || candidate.status === "completed"
        )
      ));
      if (conflictingJob) {
        sendJson(response, 409, {
          error: "Nie można wyzerować checkpointu, dopóki import tego towarzystwa trwa albo czeka na zapis.",
        });
        return true;
      }
      const result = await portfolioImportState.resetImportCheckpoint(checkpointKey);
      sendJson(response, 200, {
        checkpointKey: result.key,
        reset: result.removed === true,
      });
    } catch (error) {
      if (error?.code === "PORTFOLIO_IMPORT_STATE_UNREADABLE") {
        sendJson(response, 500, {
          error: "Nie można bezpiecznie odczytać pliku checkpointów. Reset nie został wykonany.",
        });
      } else {
        sendJson(response, 400, { error: "Nieprawidłowy klucz checkpointu importu." });
      }
    } finally {
      portfolioCheckpointResetsInProgress.delete(insurerId);
    }
    return true;
  }

  const consumedJobMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/automation\/jobs\/([a-f0-9-]+)\/consumed$/i);
  if (consumedJobMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    const payload = await readJsonBody(request, { limit: MAX_PORTFOLIO_REQUEST_BODY });
    const job = jobs.get(consumedJobMatch[1]);
    if (!job) {
      sendJson(response, 404, { error: "Nie znaleziono importu portfela." });
      return true;
    }
    try {
      await consumeCompletedPortfolioJob(job, payload);
      sendJson(response, 200, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, Number(error?.statusCode) || 500, {
        error: error?.message || "Nie udało się zatwierdzić zapisu importu portfela.",
      });
    }
    return true;
  }

  const pdfRetryJobMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/automation\/jobs\/([a-f0-9-]+)\/pdf-retry$/i);
  if (pdfRetryJobMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await readJsonBody(request);
    const job = jobs.get(pdfRetryJobMatch[1]);
    if (!job) {
      sendJson(response, 404, { error: "Nie znaleziono importu portfela." });
      return true;
    }
    if (job.kind !== "portfolio" || !PDF_RETRY_JOB_STATUSES.has(job.status)) {
      sendJson(response, 409, { error: "Ten import nie jest gotowy do ponowienia dokumentów PDF." });
      return true;
    }
    try {
      
      
      if (!job.pdfRetryRequestPromise) {
        job.pdfRetryRequestPromise = requestJobPdfManualRetry(job);
      }
      const operation = job.pdfRetryRequestPromise;
      try {
        await operation;
      } finally {
        if (job.pdfRetryRequestPromise === operation) delete job.pdfRetryRequestPromise;
      }
      sendJson(response, 200, { job: getPublicJob(job) });
    } catch (error) {
      sendJson(response, Number(error?.statusCode) || 503, {
        error: Number(error?.statusCode) === 409
          ? error.message
          : "Nie udało się zapisać ponowienia dokumentów PDF.",
      });
    }
    return true;
  }

  const cancelQuoteBatchMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/automation\/quote-batches\/([a-z0-9][a-z0-9-]{7,79})\/cancel$/i);
  if (cancelQuoteBatchMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    try {
      
      
      const cancellation = cancelQuoteBatchById(cancelQuoteBatchMatch[1]);
      
      
      
      
      request.on("error", () => {});
      request.resume();
      const batchJobs = await cancellation;
      sendJson(response, 200, {
        cancelled: true,
        jobs: batchJobs.map((job) => getPublicJob(job)),
      });
    } catch {
      sendJson(response, 400, { error: "Nie udało się zatrzymać paczki kalkulacji." });
    }
    return true;
  }

  const cancelJobMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/automation\/jobs\/([a-f0-9-]+)\/cancel$/i);
  if (cancelJobMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await readJsonBody(request);
    const job = jobs.get(cancelJobMatch[1]);
    if (!job) {
      sendJson(response, 404, { error: "Nie znaleziono zadania." });
      return true;
    }
    
    if (job.cancelledByUser === true) {
      await job.cancellationPromise?.catch(() => {});
      sendJson(response, 200, { job: getPublicJob(job) });
      return true;
    }
    
    
    
    
    if (
      job.watchdogExpired === true
      || (TERMINAL_JOB_STATUSES.has(job.status)
        && job.status !== "manual_required"
        && job.status !== "manual_ready")
    ) {
      sendJson(response, 409, { error: "To zadanie jest już zakończone." });
      return true;
    }
    await cancelJobByUser(job);
    sendJson(response, 200, { job: getPublicJob(job) });
    return true;
  }

  const manualJobMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/automation\/jobs\/([a-f0-9-]+)\/manual$/i);
  if (manualJobMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    await readJsonBody(request);
    const job = jobs.get(manualJobMatch[1]);
    if (!job) {
      sendJson(response, 404, { error: "Nie znaleziono kalkulacji." });
      return true;
    }
    if (
      job.watchdogExpired === true
      || job.status !== "manual_required"
      || job.manualAvailable !== true
      || (job.kind === "quote" && isQuoteBatchCancelled(job.clientBatchId))
    ) {
      sendJson(response, 409, { error: "Ta kalkulacja nie oczekuje na poprawienie ręczne." });
      return true;
    }
    try {
      const credentials = { ...job.request, password: "" };
      if (job.insurerId === "warta") credentials.password = await credentialVault.loadWartaPassword();
      else if (job.insurerId === "generali") credentials.password = await credentialVault.loadGeneraliPassword();
      else if (job.insurerId === "mtu") credentials.password = await credentialVault.loadMtuPassword();
      else if (job.insurerId === "hestia") credentials.password = await credentialVault.loadHestiaPassword();
      else if (job.insurerId === "trasti") credentials.password = await credentialVault.loadTrastiPassword();
      else if (job.insurerId === "wiener") credentials.password = await credentialVault.loadWienerPassword();
      else if (job.insurerId === "compensa") credentials.password = await credentialVault.loadCompensaPassword();
      else if (job.insurerId === "allianz") credentials.password = await credentialVault.loadAllianzPassword();
      else throw new Error("Nieznane towarzystwo kalkulacji.");
      if (!credentials.password) throw new Error(`Brakuje zapisanego hasła do ${job.insurer}.`);
      
      
      if (job.watchdogExpired === true || (job.kind === "quote" && isQuoteBatchCancelled(job.clientBatchId))) {
        credentials.password = "";
        sendJson(response, 409, { error: "Ta kalkulacja została już zatrzymana." });
        return true;
      }
      updateJob(job, {
        status: "queued",
        title: job.kind === "portfolio"
          ? `Otwieranie ${job.insurer} do poprawienia ścieżki importu…`
          : `Otwieranie ${job.insurer} do poprawienia ręcznego…`,
        detail: job.kind === "portfolio"
          ? "Przejdź od strony głównej portalu do listy polis i dokończ import."
          : "Dokończ czynność w otwartym oknie.",
        premiums: [],
        policies: [],
        manualAvailable: false,
      });
      if (job.insurerId === "warta") enqueueWartaJob(job, credentials, { forceManual: true });
      else if (job.insurerId === "generali" && job.kind === "portfolio") enqueueGeneraliPortfolioJob(job, credentials);
      else if (job.insurerId === "generali") enqueueGeneraliJob(job, credentials, { forceManual: true });
      else if (job.insurerId === "mtu" && job.kind === "portfolio") enqueueMtuPortfolioJob(job, credentials, { forceManual: true });
      else if (job.insurerId === "mtu") enqueueMtuJob(job, credentials, { forceManual: true });
      else if (job.insurerId === "hestia") enqueueHestiaPortfolioJob(job, credentials);
      else if (job.insurerId === "trasti" && job.kind === "portfolio") enqueueTrastiPortfolioJob(job, credentials);
      else if (job.insurerId === "trasti") enqueueTrastiJob(job, credentials, { forceManual: true });
      else if (job.insurerId === "wiener" && job.kind === "portfolio") enqueueWienerPortfolioJob(job, credentials);
      else if (job.insurerId === "compensa" && job.kind === "portfolio") enqueueCompensaPortfolioJob(job, credentials);
      else if (job.insurerId === "compensa") enqueueCompensaJob(job, credentials, { forceManual: true });
      else if (job.insurerId === "allianz" && job.kind === "portfolio") enqueueAllianzPortfolioJob(job, credentials);
      else if (job.insurerId === "allianz") enqueueAllianzJob(job, credentials, { forceManual: true });
      else enqueueWienerJob(job, credentials, { forceManual: true });
      sendJson(response, 202, { job: getPublicJob(job) });
    } catch (error) {
      updateJob(job, {
        status: "manual_required",
        title: job.kind === "portfolio"
          ? `${job.insurer} nadal wymaga poprawienia ścieżki importu`
          : `${job.insurer} nadal wymaga poprawienia ręcznego`,
        detail: friendlyAutomationErrorDetail(error, "Nie udało się uruchomić Google Chrome."),
        manualAvailable: true,
      });
      sendJson(response, 400, { error: job.detail, job: getPublicJob(job) });
    }
    return true;
  }

  const focusWindowMatch = request.method === "POST"
    && url.pathname.match(/^\/api\/automation\/windows\/(warta|generali|mtu|trasti|wiener|compensa|allianz|pzu|insly)\/focus$/i);
  if (focusWindowMatch) {
    if (!isTrustedMutationRequest(request)) {
      sendJson(response, 403, { error: "Żądanie nie pochodzi z lokalnej aplikacji Baza Polis." });
      return true;
    }
    const payload = await readJsonBody(request);
    const insurerId = focusWindowMatch[1].toLowerCase();
    const expectedRegistration = String(payload?.registration || "").toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 12);
    const expectedPesel = String(payload?.pesel || "").replace(/\D/g, "").slice(0, 11);
    let matchesLastJob = true;
    if (expectedRegistration || expectedPesel) {
      let latestJob = null;
      for (const job of jobs.values()) {
        if (job.insurerId !== insurerId) continue;
        if (!latestJob || (job.createdAt || 0) > (latestJob.createdAt || 0)) latestJob = job;
      }
      if (latestJob) {
        const jobRegistration = String(latestJob.request?.registration || "").toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 12);
        const jobPesel = String(latestJob.request?.pesel || "").replace(/\D/g, "").slice(0, 11);
        matchesLastJob = (!expectedRegistration || jobRegistration === expectedRegistration)
          && (!expectedPesel || jobPesel === expectedPesel);
      }
    }
    const automations = {
      warta: wartaAutomation,
      generali: generaliAutomation,
      mtu: mtuAutomation,
      trasti: trastiAutomation,
      wiener: wienerAutomation,
      compensa: compensaAutomation,
      allianz: allianzAutomation,
      pzu: pzuAutomation,
      insly: inslyAutomation,
    };
    const automation = automations[insurerId];
    let focused = false;
    if (matchesLastJob) {
      try {
        focused = (await automation?.focusWindow?.()) === true;
      } catch {
        focused = false;
      }
    }
    sendJson(response, 200, { focused });
    return true;
  }

  
  if (request.method === "GET" && url.pathname === "/api/automation/jobs") {
    const allJobs = [...jobs.values()]
      .filter((job) => (
        url.searchParams.get("unconsumedPortfolio") !== "1"
        || (
          job.kind === "portfolio"
          && (
            
            
            
            RUNNING_PORTFOLIO_JOB_STATUSES.has(job.status)
            || job.status === "completed"
            || (
              (job.insurerId === "warta" || job.insurerId === "wiener" || job.insurerId === "pzu" || job.insurerId === "mtu" || job.insurerId === "hestia" || job.insurerId === "trasti" || job.insurerId === "generali")
              && job.status === "consumed"
              && job.pdfRetry?.manualRetryAvailable === true
            )
          )
        )
      ))
      .sort((left, right) => (right.createdAt || 0) - (left.createdAt || 0))
      .map(getPublicJob);
    sendJson(response, 200, { jobs: allJobs });
    return true;
  }

  const jobMatch = request.method === "GET" && url.pathname.match(/^\/api\/automation\/jobs\/([a-f0-9-]+)$/i);
  if (jobMatch) {
    const job = jobs.get(jobMatch[1]);
    if (!job) {
      sendJson(response, 404, { error: "Nie znaleziono kalkulacji." });
    } else {
      sendJson(response, 200, { job: getPublicJob(job) });
    }
    return true;
  }
  return false;
}

async function serveStaticFile(request, response, url) {
  const requestedPath = url.pathname === "/" ? "/start.htm" : url.pathname;
  let relativePath;
  try {
    relativePath = decodeURIComponent(requestedPath).replace(/^\/+/, "");
  } catch {
    sendJson(response, 400, { error: "Nieprawidłowy adres." });
    return;
  }
  
  
  
  const BACKSLASH = String.fromCharCode(92);
  const pathSegments = relativePath.split("/");
  const containsUnsafeSegment = pathSegments.some((segment) => (
    !segment
    || segment === "."
    || segment === ".."
    || segment.includes(BACKSLASH)
    || segment.includes(":")
    || [...segment].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)
  ));
  if (containsUnsafeSegment) {
    sendJson(response, 404, { error: "Nie znaleziono pliku." });
    return;
  }
  const isAllowed = PUBLIC_FILES.has(relativePath)
    || PUBLIC_DIRECTORIES.some((directory) => relativePath.startsWith(directory));
  if (!isAllowed) {
    sendJson(response, 404, { error: "Nie znaleziono pliku." });
    return;
  }
  
  const diskRelativePath = relativePath === "start.htm" ? "pliki/start.htm" : relativePath;
  const filePath = resolve(ROOT_DIRECTORY, diskRelativePath);
  
  if (filePath !== FILES_DIRECTORY && !filePath.startsWith(`${FILES_DIRECTORY}${sep}`)) {
    sendJson(response, 403, { error: "Brak dostępu." });
    return;
  }
  try {
    const fileStats = await stat(filePath);
    if (!fileStats.isFile()) throw new Error("Not a file");
    
    
    
    
    
    const entityTag = `"${fileStats.size.toString(16)}-${Math.trunc(fileStats.mtimeMs).toString(16)}"`;
    const setStaticCacheHeaders = () => {
      applyCommonHeaders(response);
      response.setHeader("Cache-Control", "no-cache");
      response.setHeader("ETag", entityTag);
      response.setHeader("Last-Modified", fileStats.mtime.toUTCString());
    };
    const ifNoneMatch = String(request.headers["if-none-match"] || "");
    if (ifNoneMatch.split(",").some((candidate) => candidate.trim() === entityTag)) {
      setStaticCacheHeaders();
      response.statusCode = 304;
      response.end();
      return;
    }
    const contents = await readFile(filePath);
    setStaticCacheHeaders();
    response.statusCode = 200;
    response.setHeader("Content-Type", CONTENT_TYPES.get(extname(filePath).toLowerCase()) || "application/octet-stream");
    response.setHeader("Content-Length", contents.length);
    response.end(contents);
  } catch {
    sendJson(response, 404, { error: "Nie znaleziono pliku." });
  }
}

const server = createServer(async (request, response) => {
  try {
    const requestHost = String(request.headers.host || "").toLocaleLowerCase("en");
    if (!ALLOWED_REQUEST_HOSTS.has(requestHost)) {
      sendJson(response, 403, { error: "Żądanie odrzucone: nieprawidłowy nagłówek Host." });
      return;
    }
    const url = new URL(request.url || "/", APP_ORIGIN);
    if (url.pathname.startsWith("/api/")) {
      if (!(await handleApiRequest(request, response, url))) {
        sendJson(response, 404, { error: "Nie znaleziono endpointu." });
      }
      return;
    }
    if (request.method !== "GET" && request.method !== "HEAD") {
      sendJson(response, 405, { error: "Niedozwolona metoda." });
      return;
    }
    await serveStaticFile(request, response, url);
  } catch (error) {
    console.error(`Lokalny serwer: ${safeJobErrorIdentifier(error)}.`);
    sendJson(response, 500, { error: "Lokalny serwer nie mógł obsłużyć żądania." });
  }
});

function cleanupOldJobs() {
  const threshold = Date.now() - JOB_RETENTION_MS;
  for (const [jobId, job] of jobs) {
    if (
      job.updatedAt < threshold
      && ["completed", "consumed", "error", "manual_required", "manual_ready"].includes(job.status)
    ) {
      jobs.delete(jobId);
      if (job.pdfDirectory) {
        void cleanupPortfolioPdfJobDirectory({
          filesDirectory: FILES_DIRECTORY,
          jobId: job.id,
          jobDirectory: job.pdfDirectory,
        }).catch(() => {
          console.error("Stary katalog tymczasowy PDF joba nie został bezpiecznie usunięty.");
        });
      }
    }
  }
}

function settleShutdownOperations(operations, timeoutMs = SHUTDOWN_CLOSE_TIMEOUT_MS) {
  const observedOperations = operations.map((operation) => Promise.resolve().then(operation));
  
  
  const allSettled = Promise.allSettled(observedOperations);
  let deadlineTimer = null;
  const deadline = new Promise((resolvePromise) => {
    deadlineTimer = globalThis.setTimeout(resolvePromise, timeoutMs);
    deadlineTimer?.unref?.();
  });
  return Promise.race([allSettled, deadline]).finally(() => {
    if (deadlineTimer !== null) globalThis.clearTimeout(deadlineTimer);
  });
}

async function shutdown() {
  if (shuttingDown) return;
  shuttingDown = true;
  
  
  const forceExitTimer = globalThis.setTimeout(() => process.exit(0), SHUTDOWN_FORCE_EXIT_MS);
  forceExitTimer?.unref?.();
  for (const job of jobs.values()) {
    if (typeof job?.pendingInput?.finish === "function") {
      job.pendingInput.finish(null);
    }
  }
  await settleShutdownOperations([
    () => generaliAutomation.close(),
    () => mtuAutomation.close(),
    () => hestiaAutomation.close(),
    () => trastiAutomation.close(),
    () => wienerAutomation.close(),
    () => compensaAutomation.close(),
    () => allianzAutomation.close(),
    () => wartaAutomation.close(),
    () => pzuAutomation.close(),
    () => inslyAutomation.close(),
    
    
    
    () => browserPool.closeAll(),
  ]);
  server.close(() => process.exit(0));
}

process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
process.on("unhandledRejection", (reason) => {
  console.error(`Nieobsłużone odrzucenie Promise: ${safeJobErrorIdentifier(reason)}.`);
});
globalThis.setInterval(cleanupOldJobs, 5 * 60 * 1000).unref();










const ABANDONED_PAGE_REAP_MS = INPUT_ANSWER_TIMEOUT_MS;
const LIVE_AUTOMATION_JOB_STATUSES = new Set([
  "queued",
  "running",
  "action_required",
  "input_required",
]);
async function reapAbandonedAutomationPages() {
  for (const [insurerId, automation] of automationByInsurerId) {
    if (insurerId === "pzu" || insurerId === "insly") continue;
    let newestActivityAt = 0;
    let hasLiveJob = false;
    for (const job of jobs.values()) {
      if (job.insurerId !== insurerId) continue;
      if (LIVE_AUTOMATION_JOB_STATUSES.has(job.status)) {
        hasLiveJob = true;
        break;
      }
      newestActivityAt = Math.max(newestActivityAt, job.updatedAt || 0);
    }
    if (hasLiveJob) continue;
    const pages = browserPool.listPages(insurerId);
    if (!pages.some((page) => page?.isClosed?.() !== true)) continue;
    if (newestActivityAt && Date.now() - newestActivityAt < ABANDONED_PAGE_REAP_MS) continue;
    try {
      await automation.close();
      console.error(`Pula przeglądarek: sprzątnięto porzucone karty ${insurerId} (okno bez opieki).`);
    } catch {
      
    }
  }
}
globalThis.setInterval(() => { void reapAbandonedAutomationPages(); }, 5 * 60 * 1000).unref();

await mkdir(join(FILES_DIRECTORY, "tmp"), { recursive: true });



void sweepOrphanedPortfolioPdfJobDirectories({
  filesDirectory: FILES_DIRECTORY,
  liveJobIds: new Set(jobs.keys()),
}).then((sweep) => {
  if (sweep.removed > 0 || sweep.failed > 0) {
    console.error(
      `Sprzątanie PDF po restarcie: usunięto ${sweep.removed} katalogów jobów, błędów ${sweep.failed}.`,
    );
  }
}).catch(() => {});


await refreshAccountPinSessionFlag();
server.listen(PORT, HOST, () => {
  console.log(`Iseca działa pod adresem ${APP_URL}`);
  diagnostykaStore.zapiszZdarzenie("start-aplikacji", {
    bootMs: Math.round(process.uptime() * 1000),
  });
  
  
  
  
  if (!chromeExecutablePath) {
    console.error("Nie znaleziono Google Chrome. Zainstaluj Chrome i uruchom aplikację ponownie.");
    return;
  }
  
  
  
  
  
  
  
  globalThis.setTimeout(() => {
    if (shuttingDown) return;
    void browserPool.prewarm(["wspolna", "generali", "allianz", "ergo"]);
  }, 20_000).unref();
  if (process.env.BAZA_POLIS_NO_OPEN === "1") return;
  const chromeProcess = spawn(chromeExecutablePath, [APP_URL], {
    detached: true,
    stdio: "ignore",
  });
  chromeProcess.unref();
});

server.on("error", (error) => {
  if (error?.code === "EADDRINUSE") {
    console.error(`Port ${PORT} jest już używany. Iseca prawdopodobnie jest już uruchomiona: ${APP_URL}`);
    console.error(`Jeśli aplikacja się nie otwiera, uruchom narzędzie "pliki\\tools\\Zatrzymaj Baza Polis.cmd", aby zamknąć zawieszony serwer.`);
  } else {
    console.error(error);
  }
  process.exitCode = 1;
});





const REJESTR_FIRM_PAMIEC = new Map();

function dzisiejszaDataRejestru() {
  const teraz = new Date();
  const miesiac = String(teraz.getMonth() + 1).padStart(2, "0");
  const dzien = String(teraz.getDate()).padStart(2, "0");
  return `${teraz.getFullYear()}-${miesiac}-${dzien}`;
}

async function znajdzNipPoRegonie(regon) {
  const czystyRegon = String(regon ?? "").replace(/\D/g, "");
  if (czystyRegon.length !== 9) {
    const blad = new Error("REGON ma 9 cyfr.");
    blad.code = "ZLY_REGON";
    throw blad;
  }
  const dzisiaj = dzisiejszaDataRejestru();
  const zapamietane = REJESTR_FIRM_PAMIEC.get(czystyRegon);
  if (zapamietane && zapamietane.dzien === dzisiaj) return zapamietane.wynik;
  let odpowiedz;
  try {
    odpowiedz = await fetch(
      `https://wl-api.mf.gov.pl/api/search/regon/${czystyRegon}?date=${dzisiaj}`,
      { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(15000) },
    );
  } catch {
    const blad = new Error("Brak połączenia z rejestrem podatników.");
    blad.code = "BLAD_POLACZENIA";
    throw blad;
  }
  if (odpowiedz.status === 429) {
    const blad = new Error("Rejestr podatników chwilowo ogranicza liczbę zapytań.");
    blad.code = "LIMIT_ZAPYTAN";
    throw blad;
  }
  if (!odpowiedz.ok) {
    const blad = new Error("Rejestr podatników nie odpowiedział poprawnie.");
    blad.code = "BLAD_REJESTRU";
    throw blad;
  }
  const dane = await odpowiedz.json().catch(() => null);
  const podmiot = dane?.result?.subject || null;
  const wynik = podmiot
    ? {
      znaleziono: true,
      nip: String(podmiot.nip ?? "").replace(/\D/g, ""),
      nazwa: String(podmiot.name ?? "").trim(),
    }
    : { znaleziono: false, nip: "", nazwa: "" };
  REJESTR_FIRM_PAMIEC.set(czystyRegon, { dzien: dzisiaj, wynik });
  return wynik;
}
