(function initFivaSmartVisaProfileEngine(global) {
  "use strict";

  if (global.FIVA?.SmartVisaProfileEngine) {
    if (typeof module !== "undefined" && module.exports) module.exports = global.FIVA.SmartVisaProfileEngine;
    return;
  }

  function clean(text = "") {
    return global.FIVA?.CleanOCRText?.normalizeExtractedText
      ? global.FIVA.CleanOCRText.normalizeExtractedText(text)
      : global.FIVA?.CleanOCRText?.cleanOCRText
        ? global.FIVA.CleanOCRText.cleanOCRText(text)
      : String(text || "").replace(/\s+/g, " ").trim();
  }

  function compact(value = "") {
    return String(value || "").replace(/\s+/g, " ").trim();
  }

  function hasData(profile = {}) {
    return Object.entries(profile || {}).some(([key, value]) => !String(key).startsWith("__") && compact(value));
  }

  function mergeFields(...parts) {
    const mapper = global.FIVA?.FivaFieldMap;
    if (mapper?.mergeFields) return mapper.mergeFields(...parts);
    const fields = {};
    const meta = {};
    parts.forEach((part) => {
      Object.entries(part || {}).forEach(([key, value]) => {
        if (key.startsWith("__") || fields[key] || !compact(value)) return;
        fields[key] = value;
      });
      Object.assign(meta, part?.__fieldMeta || {});
    });
    return { ...fields, __fieldMeta: meta };
  }

  function metaFromIntent(intentMeta = {}, existing = {}) {
    return Object.fromEntries(Object.entries(intentMeta || {}).map(([key, value]) => [key, {
      confidence: Number(existing[key]?.confidence || value.confidence || 94),
      source: existing[key]?.source || value.source || "intent",
      verified: existing[key]?.verified === true || value.verified === true
    }]));
  }

  function sourceConfidenceFromMeta(profile = {}, meta = {}) {
    return Object.fromEntries(Object.entries(meta || {}).map(([key, value]) => [key, {
      value: profile[key] || "",
      confidence: Math.max(0, Math.min(1, Number(value?.confidence || 0) / 100)),
      source: value?.source || "unknown"
    }]));
  }

  function reconcileDateFields(merged = {}, structured = {}, passport = {}) {
    const next = { ...merged, __fieldMeta: { ...(merged.__fieldMeta || {}) } };
    ["dateOfBirth", "passportIssueDate", "passportExpiryDate"].forEach((field) => {
      const structuredValue = structured?.[field] || "";
      const passportValue = passport?.[field] || "";
      if (!passportValue || !structuredValue || passportValue === structuredValue) return;

      const structuredMeta = structured?.__fieldMeta?.[field] || {};
      const passportMeta = passport?.__fieldMeta?.[field] || {};
      const passportTrusted = /^(mrz|passport_text|text)$/i.test(passportMeta.source || "")
        && Number(passportMeta.confidence || 0) >= Number(structuredMeta.confidence || 0);
      const structuredMixed = structuredMeta.mixedLabels === true;
      if (!passportTrusted && !structuredMixed) return;

      next[field] = passportValue;
      next.__fieldMeta[field] = passportMeta.confidence ? passportMeta : structuredMeta;
    });
    if (next.dateOfBirth) next.dob = next.dateOfBirth;
    return next;
  }

  function sourceOptions(source = {}) {
    const siteUrl = source.siteUrl || "";
    const allowDefaultCountry = source.allowDefaultCountry === true;
    return {
      ...source,
      siteUrl,
      allowDefaultCountry,
      currentUploadOnly: true
    };
  }

  function normalizeProfile(profile = {}, source = {}) {
    const resolver = global.FIVA?.FieldIntentResolver;
    if (!resolver?.resolveProfile) return { profile: { ...profile }, fields: { ...profile }, missing: [] };
    const resolved = resolver.resolveProfile(profile, sourceOptions(source));
    const existingMeta = profile.__fieldMeta || {};
    const meta = {
      ...existingMeta,
      ...metaFromIntent(resolved.meta, existingMeta)
    };
    const resolvedProfile = {
      ...resolved.profile,
      __fieldMeta: meta
    };
    resolvedProfile.sourceConfidence = sourceConfidenceFromMeta(resolvedProfile, meta);
    return {
      profile: resolvedProfile,
      fields: {
        ...resolvedProfile
      },
      missing: resolved.missing || [],
      meta
    };
  }

  function parseText(text = "", source = {}) {
    const cleanedText = clean(text);
    const structured = global.FIVA?.FivaFieldMap?.parseStructured?.(cleanedText) || {};
    const passport = global.FIVA?.PassportProfileExtractor?.extract?.(cleanedText)
      || global.FIVA?.PassportParser?.parse?.(cleanedText)
      || {};
    const merged = reconcileDateFields(mergeFields(structured, passport), structured, passport);
    const normalized = normalizeProfile(merged, {
      ...source,
      textLength: cleanedText.length
    });
    const fields = mergeFields(merged, normalized.fields);
    return {
      cleanedText,
      fields,
      profile: normalized.profile,
      missing: normalized.missing,
      source: {
        ...source,
        textLength: cleanedText.length
      }
    };
  }

  function normalizeAnalysis(analysis = {}, options = {}) {
    const source = {
      ...(analysis.source || {}),
      ...options
    };
    const baseProfile = analysis.profile || analysis || {};
    const normalized = normalizeProfile(baseProfile, source);
    if (!hasData(normalized.profile)) return analysis;
    return {
      ...analysis,
      profile: Object.fromEntries(Object.entries(normalized.profile).filter(([key]) => key !== "__fieldMeta")),
      normalizedProfile: normalized.profile,
      fields: analysis.fields || [],
      missing: normalized.missing,
      source
    };
  }

  const SmartVisaProfileEngine = Object.freeze({
    clean,
    hasData,
    mergeFields,
    normalizeAnalysis,
    normalizeProfile,
    parseText
  });

  const SmartVisaProfileExtractor = Object.freeze({
    extract: parseText,
    normalizeProfile,
    parseText
  });

  global.FIVA = Object.assign(global.FIVA || {}, { SmartVisaProfileEngine, SmartVisaProfileExtractor });

  if (typeof module !== "undefined" && module.exports) {
    module.exports = SmartVisaProfileEngine;
  }
})(typeof globalThis !== "undefined" ? globalThis : this);
