(function registerHestiaBusinessPropertyPolicyParser(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 { normalizeForDetection, firstMatch, 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 && /^RODZAJ PROWADZONEJ DZIALALNOSCI$/.test(normalizeForDetection(line))
    ));
    return lines.slice(startIndex, endIndex > startIndex ? endIndex : startIndex + 6);
  }

  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 period = findInsurancePeriod(allText);
    const policy = {
      clientName: firstMatch(holderText, [
        /Ubezpieczaj[aą]cy(?:\s*\/\s*Ubezpieczony)?\s*\n([^,\n]{3,180})(?=\s*,\s*DATA URODZENIA\s*:)/i,
      ]),
      identityNumber: firstMatch(holderText, [
        /REGON\s*:\s*([0-9][0-9 .-]{6,19})/i,
        /(?:PESEL|NIP)\s*:\s*([0-9][0-9 .-]{7,18})/i,
      ]).replace(/\D/g, ""),
      contact: "",
      policyNumber: firstMatch(allText, [/Polisa\s+MF-M\s+([0-9A-Z/-]{6,})/i]),
      registration: "Firma",
      clientAddress: findClientAddress(holderText),
      validFrom: period[0],
      validUntil: period[1],
      premium: cleanPremium(firstMatch(allText, [
        /RAZEM DO ZAPŁATY\s+([0-9][0-9 .,'\u00a0]*)/i,
      ])),
      riskSummary: helpers.findRiskSummary(allText),
    };
    const missingRequiredFields = ["clientName", "policyNumber", "validUntil"]
      .filter((fieldName) => !policy[fieldName]);
    if (missingRequiredFields.length > 0) {
      const error = new Error("Nie udało się pewnie odczytać danych z polisy mienia firmowego 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-firma-mienie",
    insurer: "Hestia",
    product: "Firma - mienie",
    detect: ({ detectionText }) => /POLISA MF-M\s+[0-9A-Z/-]+/.test(detectionText)
      && /ERGO HESTIA/.test(detectionText),
    parse: parsePolicy,
  });
})(globalThis);
