import type { ContentSample } from "../../audit/scrapers/firecrawl-content";
import type { PageData } from "../../audit/types";
import type { VoiceSearchGap, VoiceSearchRecommendation } from "../types";

export interface FaqReadabilityResult {
  score: number;
  pagesChecked: number;
  pagesWithFaq: number;
  pagesWithFaqSchema: number;
  pagesWithShortAnswers: number;
  gaps: VoiceSearchGap[];
  recommendations: VoiceSearchRecommendation[];
}

const FAQ_SCHEMA_PATTERN = /"@type"\s*:\s*"FAQPage"/;

// Short answer indicator: paragraph of 40 words or fewer immediately after a question heading
const SHORT_ANSWER_RE = /^#{2,4}\s+.+\?[^\n]*\n+(?:[^\n]{1,250}\n)/m;

function hasFaqSchema(markdown: string): boolean {
  return FAQ_SCHEMA_PATTERN.test(markdown);
}

function hasShortAnswers(markdown: string): boolean {
  return SHORT_ANSWER_RE.test(markdown);
}

export function checkFaqReadability(
  pages: PageData[],
  samples: ContentSample[],
): FaqReadabilityResult {
  const sampleMap = new Map(samples.map((s) => [s.url, s]));

  let pagesWithFaq = 0;
  let pagesWithFaqSchema = 0;
  let pagesWithShortAnswers = 0;
  const checked = Math.min(pages.length, samples.length);

  for (const page of pages) {
    const sample = sampleMap.get(page.url);
    if (!sample) continue;

    const md = sample.markdown ?? "";
    if (sample.hasFAQ) pagesWithFaq++;
    if (hasFaqSchema(md)) pagesWithFaqSchema++;
    if (hasShortAnswers(md)) pagesWithShortAnswers++;
  }

  const faqRatio = checked > 0 ? pagesWithFaq / checked : 0;
  const schemaRatio = checked > 0 ? pagesWithFaqSchema / checked : 0;
  const shortAnswerRatio = checked > 0 ? pagesWithShortAnswers / checked : 0;

  // Score: FAQ presence (30%) + short concise answers (40%) + FAQ schema markup (30%)
  const score = Math.round((faqRatio * 30 + shortAnswerRatio * 40 + schemaRatio * 30) * 100) / 100;

  const gaps: VoiceSearchGap[] = [];
  const recommendations: VoiceSearchRecommendation[] = [];

  if (faqRatio < 0.2) {
    gaps.push({
      dimension: "faq-readability",
      gap: "FAQ sections absent on most pages",
      impactDescription: "FAQ content is the most direct structural match for voice query patterns; its absence removes the primary retrieval surface for voice responses.",
      implementationDifficulty: "moderate",
      estimatedScoreLift: 16,
    });
    recommendations.push({
      title: "Add FAQ sections to service and landing pages",
      impact: "high",
      effort: "day",
      rationale: "FAQ blocks provide pre-formatted question-answer pairs that voice engines can extract verbatim as spoken responses.",
    });
  }

  if (schemaRatio < 0.15 && faqRatio > 0.1) {
    gaps.push({
      dimension: "faq-readability",
      gap: "FAQ content present but FAQPage schema not implemented",
      impactDescription: "FAQPage schema enables direct extraction by voice engines and rich result eligibility; its absence means FAQ content must be inferred rather than read structurally.",
      implementationDifficulty: "easy",
      estimatedScoreLift: 11,
    });
    recommendations.push({
      title: "Implement FAQPage structured data on pages with FAQ sections",
      impact: "high",
      effort: "hour",
      rationale: "FAQPage schema is the single highest-ROI voice markup change: easy to implement, directly parseable by voice engines, and eligible for rich results.",
    });
  }

  if (shortAnswerRatio < 0.2) {
    gaps.push({
      dimension: "faq-readability",
      gap: "Answers are too long for voice response extraction",
      impactDescription: "Voice assistants select answers of 40-60 words; multi-paragraph answers are skipped in favor of more concise competing sources.",
      implementationDifficulty: "moderate",
      estimatedScoreLift: 8,
    });
    recommendations.push({
      title: "Add concise 1-2 sentence direct answer immediately after each FAQ question",
      impact: "medium",
      effort: "day",
      rationale: "Voice response extraction favors the first complete sentence after a question; leading with the direct answer before elaboration increases selection rate.",
    });
  }

  return {
    score,
    pagesChecked: checked,
    pagesWithFaq,
    pagesWithFaqSchema,
    pagesWithShortAnswers,
    gaps,
    recommendations,
  };
}
