(function registerHestiaStandardCommunicationPolicyParser(globalScope) {
  "use strict";

  const registry = globalScope.PolicyPdfParserRegistry;
  const helpers = globalScope.PolicyPdfParserHelpers;
  if (!registry || !helpers) throw new Error("Najpierw wczytaj wspólny silnik importu polis PDF.");
  const hestiaCommon = globalScope.HestiaPolicyParserCommon;
  if (!hestiaCommon) throw new Error("Najpierw wczytaj wspólny parser Hestii (afbulhgrbezwnsyxjotopfireaualjcslosoizmuzlmyyoqxngjcj.js).");

  const {
    normalizeLine,
    normalizeForDetection,
    firstMatch,
    normalizeVehicleIdentifier,
    findVehicleMakeAndModel,
    findFirstRegistrationDate,
    findVehicleExtraDetails,
    findClientAddress,
    cleanPremium,
  } = helpers;

  function getPolicyHolderSection(lines) {
    const startIndex = lines.findIndex((line) => (
      /^UBEZPIECZAJACY(?:\s*\/\s*UBEZPIECZONY)?$/.test(normalizeForDetection(line))
    ));
    if (startIndex < 0) return [];
    const endIndex = lines.findIndex((line, index) => (
      index > startIndex && /^UBEZPIECZONY POJAZD$/.test(normalizeForDetection(line))
    ));
    return lines.slice(startIndex, endIndex > startIndex ? endIndex : startIndex + 6);
  }

  function findIdentityNumber(holderText) {
    const regon = firstMatch(holderText, [/REGON\s*:\s*([0-9][0-9 .-]{6,19})/i]).replace(/\D/g, "");
    if (regon) return regon;
    const pesel = firstMatch(holderText, [/PESEL\s*:\s*([0-9][0-9 .-]{9,15})/i]).replace(/\D/g, "");
    if (pesel) return pesel;
    return firstMatch(holderText, [/NIP\s*:\s*([0-9][0-9 .-]{8,15})/i]).replace(/\D/g, "");
  }

  function findInsurancePeriod(allText) {
    const match = allText.match(
      /Okres ubezpieczenia\s+od\s+(\d{4}-\d{2}-\d{2})(?:\s+\d{1,2}:\d{2})?\s+do\s+(\d{4}-\d{2}-\d{2})(?:\s+\d{1,2}:\d{2})?/i,
    );
    return match ? [match[1], match[2]] : ["", ""];
  }

  function parsePolicy({ lines, allText }) {
    const holderText = getPolicyHolderSection(lines).join("\n");
    const insurancePeriod = findInsurancePeriod(allText);
    const policy = {
      clientName: firstMatch(holderText, [
        /Ubezpieczaj[aą]cy(?:\s*\/\s*Ubezpieczony)?\s*\n([^,\n]{3,180})(?=\s*,\s*DATA URODZENIA\s*:)/i,
        
        
        /Ubezpieczaj[aą]cy(?:\s*\/\s*Ubezpieczony)?\s*\n([^\n]{3,180}?)(?=\s*\n\d{2}-\d{3}\s)/i,
      ]),
      identityNumber: findIdentityNumber(holderText),
      contact: "",
      policyNumber: firstMatch(allText, [
        /Polisa\s+(?:SOCT|MF-Kom)\s+([0-9A-Z/-]{6,})/i,
      ]),
      registration: firstMatch(allText, [
        /Ubezpieczony pojazd[\s\S]{0,500}?,\s*([A-Z]{1,3}[A-Z0-9]{3,8})\s*,\s*ROK PRODUKCJI\s*:/i,
      ]).replace(/\s+/g, "").toLocaleUpperCase("pl"),
      ...findVehicleMakeAndModel(allText),
      vin: normalizeVehicleIdentifier(firstMatch(allText, [
        /\bVIN\s*:?\s*([A-Z0-9][A-Z0-9 -]{3,23})/i,
      ])),
      firstRegistrationDate: findFirstRegistrationDate(allText),
      ...findVehicleExtraDetails(allText),
      clientAddress: findClientAddress(holderText),
      validFrom: insurancePeriod[0],
      validUntil: insurancePeriod[1],
      premium: cleanPremium(firstMatch(allText, [
        /RAZEM DO ZAPŁATY\s+([0-9][0-9 .,'\u00a0]*)/i,
      ])),
      riskSummary: hestiaCommon.findCommunicationRiskSummary(allText),
    };
    const missingRequiredFields = ["clientName", "policyNumber", "registration", "validUntil"]
      .filter((fieldName) => !policy[fieldName]);
    if (missingRequiredFields.length > 0) {
      const error = new Error("Nie udało się pewnie odczytać danych z polisy komunikacyjnej Hestii.");
      error.code = "POLICY_FIELDS_MISSING";
      error.insurer = "Hestia";
      error.missingFields = missingRequiredFields;
      throw error;
    }
    return {
      policy,
      missingOptionalFields: ["identityNumber", "validFrom", "premium", "riskSummary"]
        .filter((fieldName) => !policy[fieldName]),
    };
  }

  registry.register({
    id: "hestia-standard-komunikacja",
    insurer: "Hestia",
    product: "Komunikacja",
    detect: ({ detectionText }) => /POLISA (?:SOCT|MF-KOM)\s+[0-9A-Z/-]+/.test(detectionText)
      && /ERGO HESTIA/.test(detectionText),
    parse: parsePolicy,
  });
})(globalThis);
