/**
 * Context Builder for the AI Avatar
 * -----------------------------------
 * Gathers the user's current context (org, brand, page) and formats
 * it into a plain-text block the AI can use to give relevant answers.
 *
 * This runs on the BACKEND — the frontend sends brandId + currentPage,
 * and this function enriches it with database info.
 */

import { prisma } from "@/lib/prisma";

export interface AvatarContext {
  /** Plain-text context block to inject into the system prompt */
  text: string;
  /** Structured data for retrieval functions to use */
  brandId: string;
  brandName: string;
  domain: string;
  orgName: string;
  currentPage: string;
  brandVoice: string | null;
  toneHints: string | null;
}

/**
 * Build a context object from the user's current state.
 *
 * @param brandId   - The brand the user has selected (e.g. "acme-corp")
 * @param currentPage - The page/module they're viewing (e.g. "/dashboard")
 * @param userId    - The Prisma user id for permission checks
 */
export async function buildAvatarContext(
  brandId: string,
  currentPage: string,
  userId: string
): Promise<AvatarContext | null> {
  // Look up the brand + its org
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: {
      organization: {
        include: { memberships: true },
      },
      profile: {
        select: { brandVoice: true, toneHints: true },
      },
    },
  });

  // Permission check — user must be a member of the org
  if (!brand) return null;
  if (!brand.organization.memberships.some((m) => m.userId === userId)) return null;

  const orgName = brand.organization.name;
  const brandName = brand.name;
  const domain = brand.domain ?? "unknown";
  const brandVoice = brand.profile?.brandVoice ?? null;
  const toneHints = brand.profile?.toneHints ?? null;

  // Build the plain-text context block
  const text = [
    `Organization: ${orgName}`,
    `Brand: ${brandName}`,
    `Website: ${domain}`,
    `Current page: ${currentPage}`,
    `Module: ${pageToModule(currentPage)}`,
    brandVoice ? `Brand voice: ${brandVoice}` : null,
    toneHints ? `Tone: ${toneHints}` : null,
  ].filter(Boolean).join("\n");

  return { text, brandId, brandName, domain, orgName, currentPage, brandVoice, toneHints };
}

/**
 * Maps a pathname to a human-readable module name.
 * This helps the AI understand what the user is looking at.
 */
function pageToModule(page: string): string {
  const map: Record<string, string> = {
    "/dashboard":               "Dashboard — overview KPIs and trends",
    "/technical-audit":         "Technical Audit — site health issues",
    "/site-performance-audit":  "Core Web Intelligence — page speed and CWV",
    "/broken-links":            "Broken Links — 404 pages, broken internal links, orphan pages",
    "/content-brief":           "SEO Content Brief — content planning",
    "/llmo-content-brief":      "LLMO Content Brief — AI search optimization",
    "/competitors":             "Competitors — competitive analysis",
    "/ai-visibility":           "AI Visibility — LLMO/AEO tracking",
    "/site-tag-analytics":      "Site Tag Analytics — attribution and revenue",
    "/local-geo":               "Local GEO — city-level visibility",
    "/execution-hub":           "Execution Hub — task management",
    "/page-studio":             "Page Studio — page builder",
    "/signals":                 "Signals Center — platform alerts",
    "/recommendations":         "Recommendations — prioritized actions",
    "/report-studio":           "Report Studio — client reporting",
    "/page-launch-tracker":     "Page Launch Tracker — launch pipeline",
    "/settings":                "Settings — account configuration",
    "/integrations":            "Integrations — connected services",
  };

  // Find the best match (longest prefix wins)
  const match = Object.keys(map)
    .filter((k) => page.startsWith(k))
    .sort((a, b) => b.length - a.length)[0];

  return match ? map[match] : "General — platform overview";
}
