/**
 * AI Avatar — Execution Hooks
 * ----------------------------
 * These functions actually DO things when the user clicks an action
 * button in the avatar panel. Each hook matches an action type.
 *
 * Hooks:
 *   create_task      → creates a real task in the Execution Hub via Prisma
 *   generate_report  → builds a short client-facing summary from page context
 *   navigate         → handled entirely on the frontend (no backend needed)
 *
 * Each hook returns a result the frontend can display as confirmation.
 */

import { prisma } from "@/lib/prisma";
import type { AvatarContext } from "./context-builder";
import { retrieveForPage } from "./retrieval";

// ─── Types ───────────────────────────────────────────────────────────────────

export interface ExecutionResult {
  /** Whether the hook succeeded */
  ok: boolean;
  /** A short message to show the user */
  message: string;
  /** Optional data (task id, summary text, etc.) */
  data?: Record<string, unknown>;
}

// ─── Create Task Hook ────────────────────────────────────────────────────────

/**
 * Creates a real task in the Execution Hub.
 *
 * The payload comes from the SuggestedAction.payload object:
 *   { title: "Fix broken links", priority: "high", category: "technical" }
 */
export async function executeCreateTask(
  ctx: AvatarContext,
  payload: Record<string, string>
): Promise<ExecutionResult> {
  const title = payload.title;
  if (!title) {
    return { ok: false, message: "Task title is required." };
  }

  // Check for duplicate (same title + brand)
  const existing = await prisma.task.findFirst({
    where: {
      brandId: ctx.brandId,
      title: { equals: title, mode: "insensitive" },
    },
  });

  if (existing) {
    return {
      ok: true,
      message: `Task already exists: "${title}"`,
      data: { taskId: existing.id, duplicate: true },
    };
  }

  // Map string values to valid enum-like values
  const priorityMap: Record<string, string> = {
    high: "high", medium: "medium", low: "low",
  };
  const categoryMap: Record<string, string> = {
    seo: "seo", technical: "technical", content: "content",
    performance: "performance", local: "local",
  };

  const task = await prisma.task.create({
    data: {
      brandId: ctx.brandId,
      title,
      description: payload.description || `Created by AI Strategist from ${ctx.currentPage}`,
      status: "todo",
      priority: priorityMap[payload.priority] || "medium",
      category: categoryMap[payload.category] || "seo",
      effort: payload.effort || "medium",
    },
  });

  return {
    ok: true,
    message: `Task created: "${title}"`,
    data: { taskId: task.id },
  };
}

// ─── Generate Report Summary Hook ────────────────────────────────────────────

/**
 * Generates a short, client-facing summary from the current page context.
 * This is meant to be copy-pasted into an email, Slack message, or report.
 *
 * Uses the same retrieval functions the AI uses for chat responses.
 */
export async function executeGenerateReport(
  ctx: AvatarContext,
  payload: Record<string, string>
): Promise<ExecutionResult> {
  const retrieval = await retrieveForPage(ctx);
  const mod = retrieval.module;
  const brand = ctx.brandName;
  const domain = ctx.domain;

  // Build a client-friendly summary from the retrieval data
  const metricsEntries = Object.entries(retrieval.metrics);
  const metricLines = metricsEntries
    .slice(0, 6)
    .map(([k, v]) => {
      // Convert camelCase to readable label
      const label = k.replace(/([A-Z])/g, " $1").replace(/^./, s => s.toUpperCase());
      return `• ${label}: ${v}`;
    })
    .join("\n");

  const reportType = payload.reportType || "general";

  const summary = [
    `📊 ${brand} — ${mod} Summary`,
    `Website: ${domain}`,
    `Report type: ${reportType}`,
    `Generated: ${new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}`,
    "",
    "Key Metrics:",
    metricLines,
    "",
    "Data Source:",
    retrieval.summary.split("\n").slice(1, 6).join("\n"),
    "",
    "— Generated by meSEO AI Strategist",
  ].join("\n");

  return {
    ok: true,
    message: `${mod} summary generated — ready to copy.`,
    data: { summary, reportType, module: mod },
  };
}

// ─── Get Related Module Links Hook ──────────────────────────────────────────

/**
 * Returns links to modules related to the current context.
 * The frontend uses these to show "Related pages" the user might want to visit.
 */
export async function executeGetRelatedLinks(
  ctx: AvatarContext
): Promise<ExecutionResult> {
  const page = ctx.currentPage;

  // Define relationships between modules
  const relatedMap: Record<string, Array<{ label: string; href: string }>> = {
    "/dashboard": [
      { label: "Technical Audit", href: "/technical-audit" },
      { label: "Site Tag Analytics", href: "/site-tag-analytics" },
      { label: "AI Visibility", href: "/ai-visibility" },
      { label: "Execution Hub", href: "/execution-hub" },
    ],
    "/technical-audit": [
      { label: "Broken Links", href: "/broken-links" },
      { label: "Core Web Intelligence", href: "/site-performance-audit" },
      { label: "Execution Hub", href: "/execution-hub" },
      { label: "Recommendations", href: "/recommendations" },
    ],
    "/site-tag-analytics": [
      { label: "Dashboard", href: "/dashboard" },
      { label: "Report Studio", href: "/report-studio" },
      { label: "Local GEO", href: "/local-geo" },
    ],
    "/competitors": [
      { label: "AI Visibility", href: "/ai-visibility" },
      { label: "SEO Content Brief", href: "/content-brief" },
      { label: "LLMO Content Brief", href: "/llmo-content-brief" },
    ],
    "/content-brief": [
      { label: "LLMO Content Brief", href: "/llmo-content-brief" },
      { label: "Page Studio", href: "/page-studio" },
      { label: "Competitors", href: "/competitors" },
    ],
    "/llmo-content-brief": [
      { label: "AI Visibility", href: "/ai-visibility" },
      { label: "SEO Content Brief", href: "/content-brief" },
      { label: "Page Studio", href: "/page-studio" },
    ],
    "/execution-hub": [
      { label: "Technical Audit", href: "/technical-audit" },
      { label: "Page Launch Tracker", href: "/page-launch-tracker" },
      { label: "Recommendations", href: "/recommendations" },
    ],
    "/local-geo": [
      { label: "Site Tag Analytics", href: "/site-tag-analytics" },
      { label: "Competitors", href: "/competitors" },
      { label: "Dashboard", href: "/dashboard" },
    ],
    "/page-launch-tracker": [
      { label: "Page Studio", href: "/page-studio" },
      { label: "Execution Hub", href: "/execution-hub" },
      { label: "SEO Content Brief", href: "/content-brief" },
    ],
  };

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

  const links = matchKey
    ? relatedMap[matchKey]
    : [
        { label: "Dashboard", href: "/dashboard" },
        { label: "Technical Audit", href: "/technical-audit" },
        { label: "Execution Hub", href: "/execution-hub" },
      ];

  return {
    ok: true,
    message: `${links.length} related modules found.`,
    data: { links },
  };
}

// ─── Router: run the right hook ─────────────────────────────────────────────

/**
 * Execute a hook by action type.
 * Returns a structured result the frontend can display.
 */
export async function executeHook(
  actionType: string,
  ctx: AvatarContext,
  payload: Record<string, string>
): Promise<ExecutionResult> {
  switch (actionType) {
    case "create_task":
      return executeCreateTask(ctx, payload);
    case "generate_report":
      return executeGenerateReport(ctx, payload);
    case "get_related_links":
      return executeGetRelatedLinks(ctx);
    default:
      return { ok: false, message: `Unknown action type: ${actionType}` };
  }
}
