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

  function findMtuClientAddress(lines) {
    const headerIndex = lines.findIndex((line) => /Ubezpieczaj[ąa]cy(?:\s*\/\s*Ubezpieczony)?/i.test(line));
    if (headerIndex < 0) return "";
    return findClientAddress(lines.slice(headerIndex + 1, headerIndex + 5).join("\n"));
  }

  function findInsurancePeriod(allText) {
    const match = allText.match(
      /Okres ubezpieczenia 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]] : ["", ""];
  }

  
  
  
  
  
  const MTU_RISK_LABELS = [
    ["OC", /ODPOWIEDZIALNOSC CYWILNA POSIADACZ|ZGODNIE Z USTAWA/],
    ["AC", /^AUTOCASCO\b/],
    ["Mini Casco", /^MINICASCO\b|^MINI CASCO\b/],
    ["Następstwa nieszczęśliwych wypadków", /NASTEPSTWA NIESZCZESLIWYCH WYPADKOW/],
    ["Szyby", /UBEZPIECZENIE SZYB\b/],
    ["Assistance", /ASSISTANCE/],
    ["Ochrona prawna", /ASYSTENT PRAWNY|OCHRONA PRAWNA/],
  ];

  function parseAmount(value) {
    const amount = Number(String(value ?? "").replace(/[\s\u00a0]/g, "").replace(",", "."));
    return Number.isFinite(amount) ? amount : null;
  }

  function findMtuRiskSummary(allText) {
    const lines = String(allText ?? "").split(/\r?\n/).map(normalizeLine).filter(Boolean);
    const normalized = lines.map(helpers.normalizeForDetection);
    const startIndex = normalized.findIndex((line) => /^PRODUKT UBEZPIECZENIOWY\b/.test(line));
    const endIndex = normalized.findIndex((line, index) => index > startIndex && /^RAZEM DO ZAPLATY\b/.test(line));
    if (startIndex < 0 || endIndex <= startIndex) return helpers.findRiskSummary(allText);
    const totalPremium = parseAmount(
      lines[endIndex].match(/RAZEM DO ZAP\u0141ATY\s*([0-9][0-9\s\u00a0]*(?:,[0-9]{2})?)/i)?.[1],
    );

    const risks = [];
    for (let index = startIndex + 1; index < endIndex; index += 1) {
      const label = MTU_RISK_LABELS.find(([, pattern]) => pattern.test(normalized[index]))?.[0];
      if (!label || risks.some((risk) => risk.label === label)) continue;
      
      
      let amount = "";
      for (let offset = 0; offset <= 1 && index + offset < endIndex; offset += 1) {
        amount = helpers.findRowTrailingAmount(lines[index + offset], totalPremium);
        if (amount) break;
      }
      risks.push({ label, amount });
    }
    if (risks.length === 0) return helpers.findRiskSummary(allText);
    return risks
      .map(({ label, amount }) => (amount ? `${label} ${amount} zł` : label))
      .join(" • ")
      .slice(0, 400);
  }

  function parseMtuPolicy({ lines, allText }) {
    const insurancePeriod = findInsurancePeriod(allText);
    const policy = {
      clientName: firstMatch(allText, [
        /Ubezpieczający(?:\s*\/\s*Ubezpieczony)?\s*\n([^,\n]{3,180})\s*,\s*DATA URODZENIA\s*:/i,
        /Ubezpieczający(?:\s*\/\s*Ubezpieczony)?\s*\n([^,\n]{3,180})(?=\n)/i,
      ]),
      identityNumber: firstMatch(allText, [
        /PESEL\s*:\s*(\d{11})/i,
        /(?:NIP|REGON)\s*:\s*([0-9][0-9 .-]{7,18})/i,
      ]).replace(/\D/g, ""),
      contact: "",
      policyNumber: firstMatch(allText, [
        /Polisa MTU komunikacja\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,
        /nr\s+nadwozia\s*:?\s*([A-Z0-9][A-Z0-9 -]{3,23})/i,
      ])),
      firstRegistrationDate: findFirstRegistrationDate(allText),
      ...findVehicleExtraDetails(allText),
      clientAddress: findMtuClientAddress(lines),
      validFrom: insurancePeriod[0],
      validUntil: insurancePeriod[1],
      premium: cleanPremium(firstMatch(allText, [
        /RAZEM DO ZAPŁATY\s*([0-9][0-9 .,'\u00a0]*)/i,
      ])),
      riskSummary: findMtuRiskSummary(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 MTU.");
      error.code = "POLICY_FIELDS_MISSING";
      error.insurer = "MTU";
      error.missingFields = missingRequiredFields;
      throw error;
    }
    return {
      policy,
      missingOptionalFields: ["identityNumber", "validFrom", "premium"]
        .filter((fieldName) => !policy[fieldName]),
    };
  }

  registry.register({
    id: "mtu",
    insurer: "MTU",
    product: "Komunikacja",
    detect: ({ detectionText }) => /POLISA MTU KOMUNIKACJA/.test(detectionText)
      || /M-JMTUKM-/.test(detectionText),
    parse: parseMtuPolicy,
  });
})(globalThis);
