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

export interface ConversationalQueryResult {
  score: number;
  pagesChecked: number;
  pagesWithQuestionH2: number;
  pagesWithNaturalLanguageTitle: number;
  pagesWithLongTailIndicators: number;
  gaps: VoiceSearchGap[];
  recommendations: VoiceSearchRecommendation[];
}

// Question-word patterns in headings (h2/h3)
const QUESTION_HEADING_RE = /^#{2,3}\s+(what|how|why|when|where|who|which|can|does|is|are|do|should|will)\b/im;

// Natural language title indicators: starts with question word or contains interrogative phrasing
const NATURAL_LANGUAGE_TITLE_RE = /^(what|how|why|when|where|who|which|can|does|is|are|do|should|will)\b/i;

// Long-tail indicators: 5+ word phrases, near-me, best X for Y
const LONG_TAIL_RE = /\b(near me|best .{3,20} for|how (to|do i|can i)|what (is|are|does)|why (is|are|does))\b/i;

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

  let pagesWithQuestionH2 = 0;
  let pagesWithNaturalLanguageTitle = 0;
  let pagesWithLongTailIndicators = 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 ?? "";
    const title = sample.title ?? sample.h1 ?? "";

    if (QUESTION_HEADING_RE.test(md)) pagesWithQuestionH2++;
    if (NATURAL_LANGUAGE_TITLE_RE.test(title)) pagesWithNaturalLanguageTitle++;
    if (LONG_TAIL_RE.test(md) || LONG_TAIL_RE.test(title)) pagesWithLongTailIndicators++;
  }

  const q2Ratio = checked > 0 ? pagesWithQuestionH2 / checked : 0;
  const titleRatio = checked > 0 ? pagesWithNaturalLanguageTitle / checked : 0;
  const longTailRatio = checked > 0 ? pagesWithLongTailIndicators / checked : 0;

  // Score: question headings (40%) + long-tail indicators (35%) + natural-language titles (25%)
  const score = Math.round((q2Ratio * 40 + longTailRatio * 35 + titleRatio * 25) * 100) / 100;

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

  if (q2Ratio < 0.25) {
    gaps.push({
      dimension: "conversational-query",
      gap: "Question-format headings absent across most pages",
      impactDescription: "Voice engines match spoken queries to pages with question-format headings; pages structured around keywords rather than questions are deprioritized for spoken responses.",
      implementationDifficulty: "moderate",
      estimatedScoreLift: 14,
    });
    recommendations.push({
      title: "Restructure service page headings as natural-language questions",
      impact: "high",
      effort: "day",
      rationale: "Aligning headings with spoken question patterns improves retrieval matching for voice queries without altering page semantics for human readers.",
    });
  }

  if (longTailRatio < 0.2) {
    gaps.push({
      dimension: "conversational-query",
      gap: "Low density of conversational long-tail signals in content",
      impactDescription: "Content optimized only for head terms lacks the conversational phrasing voice assistants match against.",
      implementationDifficulty: "moderate",
      estimatedScoreLift: 10,
    });
    recommendations.push({
      title: "Add 'near me' and 'how to' variant content blocks to high-intent pages",
      impact: "medium",
      effort: "day",
      rationale: "Conversational long-tail phrasing directly mirrors the query patterns voice assistants submit to retrieval engines.",
    });
  }

  return {
    score,
    pagesChecked: checked,
    pagesWithQuestionH2,
    pagesWithNaturalLanguageTitle,
    pagesWithLongTailIndicators,
    gaps,
    recommendations,
  };
}
