(function registerWienerAgroPolicyParser(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, toIsoDate, findClientAddress, cleanPremium } = helpers;

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

  function findContact(allText) {
    const email = firstMatch(allText, [/Adres e-?mail\s*:\s*([^\s\n,;]+@[^\s\n,;]+)/i]);
    const phone = firstMatch(allText, [/Telefon kontaktowy\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 findAgroRiskSummary(allText) {
    const ocPremium = cleanPremium(firstMatch(allText, [
      /Składka za ubezpieczenie obowiązkowe OC rolników\s*\(OCR\)\s*:\s*([0-9][0-9 .,'\u00a0]*)\s*zł/i,
    ]));
    const genericRisks = helpers.findRiskSummary(allText)
      .split(" • ")
      .filter((risk) => risk && !/^OC rolnika(?:\s|$)/.test(risk));
    if (ocPremium) genericRisks.unshift(`OC rolnika ${ocPremium} zł`);
    return genericRisks.join(" • ").slice(0, 400);
  }

  function parsePolicy({ allText }) {
    const period = findInsurancePeriod(allText);
    const policy = {
      clientName: firstMatch(allText, [
        /Imię i nazwisko\s*:\s*([^\n]{3,180})/i,
        /Nazwa\s*:\s*([^\n]{3,180})/i,
      ]),
      identityNumber: firstMatch(allText, [
        /Nr PESEL\s*:\s*(\d{11})/i,
        /(?:NIP|REGON)\s*:\s*([0-9][0-9 .-]{7,18})/i,
      ]).replace(/\D/g, ""),
      contact: findContact(allText),
      policyNumber: firstMatch(allText, [/Seria i numer\s+([A-Z0-9/-]{6,})/i]),
      registration: "Rolne",
      clientAddress: findClientAddress(firstMatch(allText, [
        /DANE OSOBOWE[\s\S]{0,500}?(Adres\s*:[^\n]{3,180})/i,
      ])),
      validFrom: period[0],
      validUntil: period[1],
      premium: cleanPremium(firstMatch(allText, [
        /Składka łączna\s*:\s*([0-9][0-9 .,'\u00a0]*)\s*zł/i,
        /([0-9][0-9 .,'\u00a0]*)\s*zł\s+Składka łączna/i,
      ])),
      riskSummary: findAgroRiskSummary(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 Wiener Pakiet AGRO.");
      error.code = "POLICY_FIELDS_MISSING";
      error.insurer = "Wiener";
      error.missingFields = missingRequiredFields;
      throw error;
    }
    return {
      policy,
      missingOptionalFields: ["identityNumber", "validFrom", "premium", "riskSummary"]
        .filter((fieldName) => !policy[fieldName]),
    };
  }

  registry.register({
    id: "wiener-agro",
    insurer: "Wiener",
    product: "Pakiet AGRO",
    detect: ({ detectionText }) => /POLISA PAKIET AGRO/.test(detectionText)
      && /COMPENSA/.test(detectionText)
      && /WIENER/.test(detectionText),
    parse: parsePolicy,
  });
})(globalThis);
