import type { SignaturePolicyEvaluation, SignaturePolicyMatrixEntry, SignaturePolicyStatus } from "@/lib/compliance/types";

const MATRIX: SignaturePolicyMatrixEntry[] = [
  {
    id: "nl-general-licitaciones",
    stateCode: "NL",
    stateName: "Nuevo Leon",
    municipalityCode: null,
    municipalityName: null,
    appliesTo: "licitaciones",
    policyStatus: "condicionado",
    policyName: "Firma electronica avanzada condicionada por convocatoria",
    evidenceRequired: [
      "Verificacion expresa en Bases/Convocatoria de admision de firma electronica",
      "Acuse de autenticidad o certificado vigente de la e.firma",
      "Respaldo de representacion legal de firmantes",
    ],
    notes: "Si no existe clausula expresa de admision, se escala a validacion legal interna.",
    sourceUrl: "https://www.nl.gob.mx/",
  },
  {
    id: "nl-san-pedro",
    stateCode: "NL",
    stateName: "Nuevo Leon",
    municipalityCode: "SPGG",
    municipalityName: "San Pedro Garza Garcia",
    appliesTo: "licitaciones",
    policyStatus: "requiere_validacion_legal",
    policyName: "Municipio con validacion legal previa obligatoria",
    evidenceRequired: [
      "Reglamento municipal vigente de adquisiciones",
      "Reglas de firma indicadas en convocatoria especifica",
      "Opinion legal documentada antes de envio",
    ],
    notes: "Configuracion conservadora para piloto: no asumir autorizacion automatica de firma electronica.",
    sourceUrl: "https://www.sanpedro.gob.mx/",
  },
];

function normalize(value: string | null | undefined) {
  return (value ?? "")
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .trim();
}

function isMatch(entry: SignaturePolicyMatrixEntry, input: { stateCode?: string | null; stateName?: string | null; municipalityName?: string | null }) {
  const stateCode = normalize(input.stateCode);
  const stateName = normalize(input.stateName);
  const municipalityName = normalize(input.municipalityName);

  const entryStateCode = normalize(entry.stateCode);
  const entryStateName = normalize(entry.stateName);
  const entryMunicipalityName = normalize(entry.municipalityName);

  const stateMatches = (stateCode && stateCode === entryStateCode) || (stateName && stateName === entryStateName);
  if (!stateMatches) {
    return false;
  }

  if (!entryMunicipalityName) {
    return true;
  }

  return Boolean(municipalityName && municipalityName === entryMunicipalityName);
}

export function evaluateSignaturePolicy(input: {
  stateCode?: string | null;
  stateName?: string | null;
  municipalityName?: string | null;
  documentType?: "BASES_LICITACION" | "CONVOCATORIA" | "ANEXOS" | "OTRO" | "REGLAMENTO" | "LEY";
}): SignaturePolicyEvaluation {
  const exactMunicipality = MATRIX.find((entry) => Boolean(entry.municipalityName) && isMatch(entry, input));
  const stateDefault = MATRIX.find((entry) => !entry.municipalityName && isMatch(entry, input));
  const chosen = exactMunicipality ?? stateDefault;

  if (!chosen) {
    return {
      policyStatus: "requiere_validacion_legal",
      policyName: "Sin certeza regulatoria local",
      evidenceRequired: [
        "Reglamento oficial vigente de la jurisdiccion",
        "Clausula explicita en la convocatoria sobre firma electronica",
        "Opinion legal interna previa al envio",
      ],
      notes: "Sin confirmacion oficial suficiente. Regla conservadora: requiere validacion legal.",
      jurisdictionLabel: input.stateName?.trim() || "Jurisdiccion no definida",
      sourceUrl: null,
    };
  }

  const documentHint = input.documentType ? `Documento base: ${input.documentType}.` : "";
  const jurisdictionLabel = chosen.municipalityName ? `${chosen.municipalityName}, ${chosen.stateName}` : chosen.stateName;

  return {
    policyStatus: chosen.policyStatus,
    policyName: chosen.policyName,
    evidenceRequired: chosen.evidenceRequired,
    notes: `${chosen.notes}${documentHint ? ` ${documentHint}` : ""}`.trim(),
    jurisdictionLabel,
    sourceUrl: chosen.sourceUrl,
  };
}

export function getSignaturePolicyStatusLabel(status: SignaturePolicyStatus) {
  if (status === "permitido") {
    return "Permitido";
  }

  if (status === "condicionado") {
    return "Condicionado";
  }

  return "Requiere validacion legal";
}

export function getSignaturePolicyTone(status: SignaturePolicyStatus) {
  if (status === "permitido") {
    return "border-[#b9e6cd] bg-[#eaf9f1] text-[#1f8b63]";
  }

  if (status === "condicionado") {
    return "border-[#f0deb0] bg-[#fff8e9] text-[#8d6308]";
  }

  return "border-[#f1c7ce] bg-[#fff1f4] text-[#b03f4f]";
}

export function listSignaturePolicyMatrix() {
  return [...MATRIX];
}
