export interface SeaportInfo {
  name: string;
  code: string;
  transitDays: string;
  handlingTerminal: string;
}

export interface CorridorData {
  id?: string;
  slug: string;
  countryName: string;
  countryCode: string;
  region: string;
  capitalCity: string;
  seaports: SeaportInfo[];
  airports: string[];
  complianceStandards: string[];
  industrialClusters: string[];
  b2bTerms: {
    incoTerms: string[];
    oceanPackaging: string;
    sampleDispatch: string;
    containerCapacity: string;
    qualityCertificates: string[];
  };
  customsNote: string;
  faqs: { question: string; answer: string }[];
  flag: string;
}

export interface CorridorAuditResult {
  wordCount: number;
  uniquenessScore: number; // percentage
  status: "SAFE" | "BORDERLINE" | "THIN";
  attributesFound: {
    seaports: boolean;
    compliance: boolean;
    industrialClusters: boolean;
    b2bTerms: boolean;
    compoundMatrix: boolean;
    customsFaqs: boolean;
    wordCountPassed: boolean;
  };
  passedCount: number;
  recommendation: string;
}

/**
 * Calculates word count from a raw string or HTML snippet
 */
export function calculateWordCount(text: string): number {
  if (!text) return 0;
  const clean = text.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
  if (!clean) return 0;
  return clean.split(/\s+/).length;
}

/**
 * Audit engine to evaluate the 7 mandatory attributes of the Anti-Doorway Guard
 */
export function auditCorridorContent(
  text: string,
  corridor: CorridorData
): CorridorAuditResult {
  const wordCount = calculateWordCount(text);
  const lowerText = text.toLowerCase();

  // 1. Check seaport & transit days
  const hasSeaports = corridor.seaports.some(
    (p) =>
      lowerText.includes(p.name.toLowerCase()) ||
      lowerText.includes(p.code.toLowerCase()) ||
      lowerText.includes("chennai port") ||
      lowerText.includes("inmaa")
  );

  // 2. Check compliance standards
  const hasCompliance = corridor.complianceStandards.some((c) =>
    lowerText.includes(c.toLowerCase().split("(")[0].trim())
  );

  // 3. Check industrial clusters
  const hasIndustrialClusters = corridor.industrialClusters.some((cluster) => {
    const cityName = cluster.split("/")[0].trim().toLowerCase();
    return lowerText.includes(cityName);
  });

  // 4. Check B2B IncoTerms & shipping
  const hasB2BTerms =
    lowerText.includes("incoterm") ||
    lowerText.includes("fob chennai") ||
    lowerText.includes("cif") ||
    lowerText.includes("fcl") ||
    lowerText.includes("ispm 15");

  // 5. Check Compound Matrix
  const compounds = ["ffkm", "fkm", "viton", "epdm", "silicone", "polyurethane", "nbr"];
  const compoundMatches = compounds.filter((comp) => lowerText.includes(comp));
  const hasCompoundMatrix = compoundMatches.length >= 3;

  // 6. Check Customs / Tariffs / FAQs
  const hasCustomsFaqs =
    lowerText.includes("customs") ||
    lowerText.includes("tariff") ||
    lowerText.includes("eori") ||
    lowerText.includes("hs code") ||
    lowerText.includes("duties") ||
    corridor.faqs.length >= 3;

  // 7. Word count check >= 350
  const wordCountPassed = wordCount >= 350;

  const attributes = {
    seaports: hasSeaports,
    compliance: hasCompliance,
    industrialClusters: hasIndustrialClusters,
    b2bTerms: hasB2BTerms,
    compoundMatrix: hasCompoundMatrix,
    customsFaqs: hasCustomsFaqs,
    wordCountPassed,
  };

  const passedCount = Object.values(attributes).filter(Boolean).length;
  // Uniqueness score baseline: each attribute contributes ~10%, word count adds up to 30%
  const uniquenessScore = Math.min(
    100,
    Math.round(
      (passedCount / 7) * 70 +
        Math.min(30, Math.floor((wordCount / 500) * 30))
    )
  );

  let status: "SAFE" | "BORDERLINE" | "THIN" = "THIN";
  if (wordCountPassed && passedCount >= 6 && uniquenessScore >= 40) {
    status = "SAFE";
  } else if (wordCount >= 250 && passedCount >= 4) {
    status = "BORDERLINE";
  }

  let recommendation = "Content adheres strictly to Google Anti-Doorway Algorithmic standards (>40% semantic uniqueness).";
  if (status === "THIN") {
    recommendation = "CRITICAL: Page lacks required country-specific technical entities and is under the 350-word threshold.";
  } else if (status === "BORDERLINE") {
    recommendation = "Add more destination port details and specific regional compliance standards to attain full SAFE status.";
  }

  return {
    wordCount,
    uniquenessScore,
    status,
    attributesFound: attributes,
    passedCount,
    recommendation,
  };
}

/**
 * Mathematical Text Similarity Algorithm (Word Bi-gram Dice's Coefficient)
 * Directly enforces the 40% similarity ceiling to guarantee anti-doorway compliance.
 */
export function calculateTextSimilarity(text1: string, text2: string): number {
  if (!text1 || !text2) return 0.0;
  const clean1 = text1.toLowerCase().replace(/[^a-z0-9\s]/g, " ").replace(/\s+/g, " ").trim();
  const clean2 = text2.toLowerCase().replace(/[^a-z0-9\s]/g, " ").replace(/\s+/g, " ").trim();

  if (clean1 === clean2) return 100.0;

  const words1 = clean1.split(" ");
  const words2 = clean2.split(" ");

  if (words1.length < 2 || words2.length < 2) {
    return clean1 === clean2 ? 100.0 : 0.0;
  }

  // Generate word bigrams
  const bigrams1 = new Set<string>();
  for (let i = 0; i < words1.length - 1; i++) {
    bigrams1.add(`${words1[i]}_${words1[i + 1]}`);
  }

  const bigrams2 = new Set<string>();
  for (let i = 0; i < words2.length - 1; i++) {
    bigrams2.add(`${words2[i]}_${words2[i + 1]}`);
  }

  let intersection = 0;
  bigrams1.forEach((bg) => {
    if (bigrams2.has(bg)) intersection++;
  });

  const total = bigrams1.size + bigrams2.size;
  if (total === 0) return 0.0;

  return Number(((2.0 * intersection) / total * 100).toFixed(1));
}

/**
 * Validates corridor/location content against all existing published corridors.
 * Strictly enforces:
 * 1. Word count >= 250 words
 * 2. Maximum similarity ceiling <= 40.0%
 */
export function validateDoorwayContent(
  candidateText: string,
  existingCorridors: { slug: string; name?: string; text: string }[]
): {
  canPublish: boolean;
  wordCount: number;
  maxSimilarity: number;
  mostSimilarCorridor: string | null;
  errors: string[];
} {
  const wordCount = calculateWordCount(candidateText);
  const errors: string[] = [];

  if (wordCount < 250) {
    errors.push(`Content word count is only ${wordCount} words (minimum 250 words required).`);
  }

  let maxSimilarity = 0;
  let mostSimilarCorridor: string | null = null;

  for (const existing of existingCorridors) {
    const sim = calculateTextSimilarity(candidateText, existing.text);
    if (sim > maxSimilarity) {
      maxSimilarity = sim;
      mostSimilarCorridor = existing.name || existing.slug;
    }
  }

  if (maxSimilarity > 40.0) {
    errors.push(
      `Text similarity is ${maxSimilarity}% with "${mostSimilarCorridor}" (exceeds 40.0% doorway ceiling).`
    );
  }

  return {
    canPublish: errors.length === 0,
    wordCount,
    maxSimilarity,
    mostSimilarCorridor,
    errors,
  };
}
