/**
 * Query Intent Reconstruction
 * ────────────────────────────
 * Infers probable search queries when the AI platform strips query context.
 * Uses landing page topic + behavioral signals + brand keywords.
 */

export interface ReconstructedIntent {
  probableQuery: string;
  intentCategory: "informational" | "transactional" | "navigational" | "commercial";
  confidence: number;
  signals: string[];
}

export function reconstructQueryIntent(args: {
  landingPage: string;
  pageTitle?: string;
  formSubmitted: boolean;
  phoneClicked: boolean;
  onSiteSearches: string[];
  brandName: string;
  brandCity?: string;
}): ReconstructedIntent {
  const signals: string[] = [];
  let confidence = 0;

  // Extract topic from URL path
  const path = args.landingPage.replace(/^\/|\/$/g, "");
  const pathParts = path.split("/").filter(Boolean);
  const pageTopic = pathParts.length > 0
    ? pathParts[pathParts.length - 1].replace(/[-_]/g, " ")
    : "";

  if (pageTopic) {
    signals.push(`page_topic: ${pageTopic}`);
    confidence += 30;
  }

  // On-site searches reveal intent
  if (args.onSiteSearches.length > 0) {
    signals.push(`searched: ${args.onSiteSearches.slice(0, 3).join(", ")}`);
    confidence += 25;
  }

  // Conversion signals reveal transactional intent
  if (args.formSubmitted) {
    signals.push("converted_via_form");
    confidence += 15;
  }
  if (args.phoneClicked) {
    signals.push("clicked_phone");
    confidence += 15;
  }

  // Page title adds context
  if (args.pageTitle && args.pageTitle.length > 5) {
    signals.push(`title: ${args.pageTitle.slice(0, 60)}`);
    confidence += 10;
  }

  // Build probable query
  const parts: string[] = [];
  if (pageTopic) parts.push(pageTopic);
  if (args.brandCity) parts.push(args.brandCity);
  if (args.onSiteSearches.length > 0) parts.push(args.onSiteSearches[0]);

  const probableQuery = parts.length > 0
    ? parts.join(" ").toLowerCase().slice(0, 100)
    : `${args.brandName} services`.toLowerCase();

  // Classify intent
  let intentCategory: ReconstructedIntent["intentCategory"] = "informational";
  if (args.formSubmitted || args.phoneClicked) {
    intentCategory = "transactional";
  } else if (args.onSiteSearches.some((s) => /price|cost|insurance|appointment|book/i.test(s))) {
    intentCategory = "commercial";
  } else if (path.includes("about") || path.includes("team") || path.includes("doctor")) {
    intentCategory = "navigational";
  }

  return {
    probableQuery: `[inferred] ${probableQuery}`,
    intentCategory,
    confidence: Math.min(confidence, 100),
    signals,
  };
}
