(function registerTuwCommunicationPolicyParser(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 {
    firstMatch,
    normalizeVehicleIdentifier,
    findVehicleMakeAndModel,
    findFirstRegistrationDate,
    findVehicleExtraDetails,
    findClientAddress,
    cleanPremium,
    
    toIsoDate,
  } = helpers;

  function getPolicyHolderSection(allText) {
    let startIndex = allText.search(/Ubezpieczający\s+Imię i nazwisko\s*:/i);
    let endPattern = /\nUbezpieczony\s*\//i;
    if (startIndex < 0) {
      
      
      startIndex = allText.search(/Dane osobowe\s*:/i);
      endPattern = /\nDane pojazdu\s*:/i;
    }
    if (startIndex < 0) return "";
    const remainder = allText.slice(startIndex);
    const endIndex = remainder.search(endPattern);
    return endIndex > 0 ? remainder.slice(0, endIndex) : remainder.slice(0, 600);
  }

  function findCompletePesel(holderText) {
    const match = holderText.match(/PESEL\s*:\s*([0-9*Xx .-]{4,24})/i);
    if (!match || /[*Xx]/.test(match[1])) return "";
    const digits = match[1].replace(/\D/g, "");
    return digits.length === 11 ? digits : "";
  }

  function findContact(holderText) {
    const email = firstMatch(holderText, [
      /e-?mail\s*:\s*([^\s\n,;]+@[^\s\n,;]+)/i,
    ]);
    const phone = firstMatch(holderText, [
      /tel\s*:\s*([+]?[0-9][0-9 ()/-]{6,20})/i,
    ]).replace(/[()\s/-]+/g, "");
    return [
      phone ? `Telefon: ${phone}` : "",
      email ? `E-mail: ${email}` : "",
    ].filter(Boolean).join("\n");
  }

  function findInsurancePeriod(allText) {
    
    
    const anchored = allText.match(
      /Okres ubezpieczenia[\s\S]{0,160}?(\d{2}-\d{2}-\d{4})\s+godz\.\s*\d{1,2}:\d{2}\s+do\s+(\d{2}-\d{2}-\d{4})/i,
    );
    const match = anchored || allText.match(
      /(\d{2}-\d{2}-\d{4})\s+godz\.\s*\d{1,2}:\d{2}\s+do\s+(\d{2}-\d{2}-\d{4})/i,
    );
    return match ? [toIsoDate(match[1]), toIsoDate(match[2])] : ["", ""];
  }

  function parseTuwCommunicationPolicy({ allText }) {
    const holderText = getPolicyHolderSection(allText);
    const insurancePeriod = findInsurancePeriod(allText);
    const policy = {
      clientName: firstMatch(holderText, [
        /Imię i nazwisko\s*:\s*([^\n]+?)(?=\s+PESEL\s*:)/i,
      ]),
      identityNumber: findCompletePesel(holderText),
      contact: findContact(holderText),
      policyNumber: firstMatch(allText, [
        /Wniosko-polisa nr\s+([0-9A-Z/-]{6,})/i,
      ]),
      registration: firstMatch(allText, [
        /numer rejestracyjny\s*:\s*([A-Z0-9][A-Z0-9 -]{3,11})/i,
      ]).replace(/\s+/g, "").toLocaleUpperCase("pl"),
      ...findVehicleMakeAndModel(allText),
      vin: normalizeVehicleIdentifier(firstMatch(allText, [
        /numer nadwozia\s*:\s*([A-Z0-9][A-Z0-9 -]{3,23})/i,
        /(?:Nr\s+VIN|VIN)\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, [
        /Składka łączna\s*:\s*([0-9][0-9 .,'\u00a0]*)\s*PLN/i,
      ])),
      riskSummary: helpers.findRiskSummary(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 klienta, numeru polisy, rejestracji lub okresu z polisy TUW.");
      error.code = "POLICY_FIELDS_MISSING";
      error.insurer = "TUW";
      error.missingFields = missingRequiredFields;
      throw error;
    }
    return {
      policy,
      missingOptionalFields: ["identityNumber", "validFrom", "premium"]
        .filter((fieldName) => !policy[fieldName]),
    };
  }

  registry.register({
    id: "tuw-komunikacja",
    insurer: "TUW",
    product: "Komunikacja",
    detect: ({ detectionText }) => /TOWARZYSTWO UBEZPIECZEN WZAJEMNYCH/.test(detectionText)
      && /WNIOSKO-POLISA NR\s+[0-9A-Z/-]+/.test(detectionText)
      && /TUW/.test(detectionText),
    parse: parseTuwCommunicationPolicy,
  });
})(globalThis);
