/**
 * AI layer (AI-001…008). AI sits on top of the modules and reads unified data through the same services;
 * anything that spends money or messages at scale goes through the approval queue (AI-008).
 */
import type Anthropic from "@anthropic-ai/sdk";
import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { audit } from "@/lib/audit";
import { emit } from "@/lib/webhooks";
import { ApiError } from "@/lib/api";
import { formatMoney, fullName, isoDay } from "@/lib/util";
import { complete, parseJson, AiUnavailable, aiConfigured } from "./gateway";
import { industryOf, type IndustryPreset } from "@/lib/industry";

/* ---------------- AI-001 content generation ---------------- */

export const GEN_KINDS: Record<string, string> = {
  ad_copy: "Facebook/Instagram ad copy: primary text (≤125 chars ideal), headline (≤40 chars), description and CTA",
  google_ad: "Google responsive search ad: 5 headlines (≤30 chars each) and 2 descriptions (≤90 chars each)",
  caption: "Social media post caption with relevant hashtags",
  email: "Marketing email: subject line, preview text and body",
  whatsapp: "WhatsApp template message (≤1024 chars, friendly, may use {{first_name}} variables, clear CTA)",
  sms: "SMS message (≤160 chars English or ≤70 chars Bangla, include brand name and opt-out hint)",
  landing: "Landing page copy: hero headline, subheadline, 3 benefit bullets, CTA button text",
  creative: "Creative variation brief: visual concept, on-image text, and copy angle",
};

export async function generateContent(ctx: Ctx, input: { kind: string; brief: string; language: "en" | "bn" | "both"; variants?: number; tone?: string }) {
  const kit = await ctx.db.query.brandKits.findFirst({ where: eq(schema.brandKits.workspaceId, ctx.workspace.id) });
  const voice = ctx.workspace.settings?.brandVoice || kit?.voice || "Confident, warm and trustworthy. Clear benefits, no hype.";
  const n = Math.min(Math.max(input.variants ?? 3, 3), 6);
  const lang = input.language === "bn" ? "Bangla (বাংলা, natural Bangladeshi usage, Bangla script)" : input.language === "both" ? "both English and Bangla (give each variant in English then Bangla)" : "English";
  const { text } = await complete(ctx, {
    feature: "generate", tier: "smart",
    system: `You are the senior copywriter for ${ctx.workspace.name}, a ${industryOf(ctx.workspace.settings).business}.${industryOf(ctx.workspace.settings).compliance ? ` Compliance: ${industryOf(ctx.workspace.settings).compliance}` : ""} Brand voice: ${voice}${input.tone ? `. Tone for this piece: ${input.tone}` : ""}. Write only claims supported by the brief. Respond with JSON only: {"variants":[{"title":"short label","content":"the full copy"}]}.`,
    messages: [{ role: "user", content: `Format: ${GEN_KINDS[input.kind] ?? input.kind}\nLanguage: ${lang}\nNumber of distinct variants: ${n}\n\nBrief:\n${input.brief}` }],
    maxTokens: 6000,
  });
  const parsed = parseJson<{ variants: { title: string; content: string }[] }>(text);
  const variants = parsed?.variants?.length ? parsed.variants : text.split(/\n-{3,}\n/).map((c, i) => ({ title: `Variant ${i + 1}`, content: c.trim() }));
  return { variants: variants.slice(0, n), voice };
}

/* ---------------- AI-002 qualification agent ---------------- */

/** Tools depend on the workspace industry: qualification fields and the name of the booked step. */
const qualTools = (ind: IndustryPreset): Anthropic.Tool[] => [
  { name: "save_qualification", description: `Save qualification answers the lead has given. Call whenever you learn ${ind.qualification.map((q) => q.ask).join(", ")}.`, input_schema: { type: "object", properties: Object.fromEntries(ind.qualification.map((q) => [q.key, { type: "string", description: q.label }])), additionalProperties: false } },
  { name: "book_next_step", description: `Book a call or ${ind.visit.toLowerCase()} once the lead agrees to a time (kind "visit" = ${ind.visit.toLowerCase()}).`, input_schema: { type: "object", properties: { kind: { type: "string", enum: ["call", "visit"] }, when_iso: { type: "string", description: "ISO 8601 date-time in the workspace timezone" }, note: { type: "string" } }, required: ["kind", "when_iso"], additionalProperties: false } },
  { name: "handoff_to_human", description: "Hand the conversation to a human agent (lead asks for a person, is upset, or asks something you cannot answer).", input_schema: { type: "object", properties: { reason: { type: "string" } }, required: ["reason"], additionalProperties: false } },
];

export async function agentReply(ctx: Ctx, conversationId: string) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv || !conv.aiAgentActive) return null;
  const contact = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, conv.contactId) }))!;
  const history = await ctx.db.select().from(schema.messages).where(eq(schema.messages.conversationId, conv.id)).orderBy(asc(schema.messages.createdAt)).limit(40);
  const last = history[history.length - 1];
  if (!last || last.direction !== "in") return null;
  const msgs: Anthropic.MessageParam[] = [];
  for (const m of history.filter((x) => x.direction !== "note")) {
    const role = m.direction === "in" ? "user" : "assistant";
    const prev = msgs[msgs.length - 1];
    if (prev && prev.role === role) prev.content = `${prev.content}\n${m.body}`;
    else msgs.push({ role, content: m.body });
  }
  if (msgs[0]?.role !== "user") msgs.unshift({ role: "user", content: "(conversation started)" });
  const known = contact.customFields as Record<string, unknown>;
  const ind = industryOf(ctx.workspace.settings);
  const system = `You are the WhatsApp/Messenger assistant for ${ctx.workspace.name}, a ${ind.business}. Goal: politely qualify the lead by learning ${ind.qualification.map((q) => q.ask).join(", ")}, then book a call or ${ind.visit.toLowerCase()}. Ask one question at a time. Reply in the language the lead uses (Bangla or English). Keep replies under 60 words. Never invent prices, availability or other facts; offer to have a team member confirm.${ind.compliance ? ` ${ind.compliance}` : ""} Known so far: ${JSON.stringify({ name: fullName(contact), interest: contact.project, ...Object.fromEntries(ind.qualification.map((q) => [q.key, known[q.key] ?? null])) })}. Workspace timezone: ${ctx.workspace.timezone}. Today: ${new Date().toISOString().slice(0, 10)}.`;
  let reply = "";
  for (let turn = 0; turn < 4; turn++) {
    const { message } = await complete(ctx, { feature: "qualification_agent", tier: "smart", system, messages: msgs, tools: qualTools(ind), maxTokens: 1500, effort: "low", cache: false });
    const toolUses = message.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");
    reply = message.content.filter((b): b is Anthropic.TextBlock => b.type === "text").map((b) => b.text).join("\n").trim() || reply;
    if (!toolUses.length || message.stop_reason !== "tool_use") break;
    msgs.push({ role: "assistant", content: message.content as Anthropic.ContentBlockParam[] });
    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const t of toolUses) results.push({ type: "tool_result", tool_use_id: t.id, content: await runQualTool(ctx, contact.id, conv.id, t.name, t.input as Record<string, string>) });
    msgs.push({ role: "user", content: results });
    const stillActive = await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, conv.id) });
    if (!stillActive?.aiAgentActive) break;
  }
  if (reply) {
    const { sendMessage } = await import("@/lib/services/messaging");
    await sendMessage(ctx, { contactId: contact.id, channel: conv.channel, body: reply, source: "ai", conversationId: conv.id });
  }
  return reply;
}

async function runQualTool(ctx: Ctx, contactId: string, conversationId: string, name: string, input: Record<string, string>) {
  const { updateContact } = await import("@/lib/services/contacts");
  if (name === "save_qualification") {
    const fields = Object.fromEntries(Object.entries(input).filter(([, v]) => v));
    await updateContact(ctx, contactId, { customFields: fields });
    const c = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contactId) }))!;
    const cf = c.customFields as Record<string, unknown>;
    const required = industryOf(ctx.workspace.settings).qualification.slice(0, 3).map((q) => q.key);
    if (required.every((k) => cf[k]) && !c.tags.includes("ai-qualified")) {
      const { addTags } = await import("@/lib/services/contacts");
      await addTags(ctx, contactId, ["ai-qualified"]);
      const deal = await ctx.db.query.deals.findFirst({ where: and(eq(schema.deals.contactId, contactId), isNull(schema.deals.wonAt), isNull(schema.deals.lostAt)) });
      const pipeline = deal ? await ctx.db.query.pipelines.findFirst({ where: eq(schema.pipelines.id, deal.pipelineId) }) : null;
      const q = pipeline?.stages.find((s) => s.id === "qualified" || s.conversionEvent === "Qualified") ?? pipeline?.stages.find((s) => /qualif/i.test(s.name));
      const cur = pipeline?.stages.find((s) => s.id === deal?.stageId);
      if (deal && q && cur && cur.order < q.order) {
        const { changeStage } = await import("@/lib/services/leads");
        await changeStage({ ...ctx, perms: { ...ctx.perms, contacts: "C" } }, deal.id, q.id);
      }
    }
    return `Saved: ${JSON.stringify(fields)}`;
  }
  if (name === "book_next_step") {
    const when = new Date(input.when_iso!);
    if (Number.isNaN(when.getTime())) return "Invalid date — ask the lead to confirm a specific day and time.";
    const c = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contactId) }))!;
    const { createActivity } = await import("@/lib/services/leads");
    await createActivity(ctx, { contactId, type: input.kind === "visit" ? "visit" : "call", title: `${input.kind === "visit" ? industryOf(ctx.workspace.settings).visit : "Call"} booked by AI agent`, body: input.note, dueAt: when, userId: c.ownerId });
    return `Booked ${input.kind} for ${when.toISOString()}. Assigned agent will confirm.`;
  }
  if (name === "handoff_to_human") {
    await ctx.db.update(schema.conversations).set({ aiAgentActive: false, status: "open" }).where(eq(schema.conversations.id, conversationId));
    const c = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contactId) }))!;
    const { notifyTeam } = await import("@/lib/services/notify");
    await notifyTeam(ctx, `AI handed off ${fullName(c)}`, input.reason, `/inbox?c=${conversationId}`, c.ownerId ? [c.ownerId] : undefined);
    return "Handed off. Tell the lead a team member will reply shortly.";
  }
  return "Unknown tool";
}

export async function startAgent(ctx: Ctx, contactId: string, channel: string) {
  const contact = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contactId) }))!;
  const { getOrCreateConversation, sendMessage } = await import("@/lib/services/messaging");
  const conv = await getOrCreateConversation(ctx, contact, channel);
  await ctx.db.update(schema.conversations).set({ aiAgentActive: true }).where(eq(schema.conversations.id, conv.id));
  const greeting = `Hi ${contact.firstName ?? "there"}! Thanks for your interest in ${contact.project ?? ctx.workspace.name}. May I ask what budget range you have in mind?`;
  return sendMessage(ctx, { contactId, channel, body: greeting, source: "ai", conversationId: conv.id });
}

/* ---------------- AI-003 predictive lead scoring ---------------- */

type Features = number[];
const FEATURE_NAMES = ["bias", "has_email", "has_phone", "src_meta", "src_google", "src_form", "src_chat", "src_other", "fast_response", "activities", "inbound_msgs", "has_project", "visit_logged", "qualified_fields"];

async function featuresFor(ctx: Pick<Ctx, "db" | "workspace">, contactIds: string[]) {
  if (!contactIds.length) return new Map<string, Features>();
  const cs = await ctx.db.select().from(schema.contacts).where(inArray(schema.contacts.id, contactIds));
  const acts = await ctx.db.select({ c: schema.activities.contactId, t: schema.activities.type, n: sql<number>`count(*)::int` }).from(schema.activities).where(inArray(schema.activities.contactId, contactIds)).groupBy(schema.activities.contactId, schema.activities.type);
  const inbound = await ctx.db.select({ c: schema.conversations.contactId, n: sql<number>`count(*)::int` }).from(schema.messages).innerJoin(schema.conversations, eq(schema.conversations.id, schema.messages.conversationId)).where(and(inArray(schema.conversations.contactId, contactIds), eq(schema.messages.direction, "in"))).groupBy(schema.conversations.contactId);
  const out = new Map<string, Features>();
  const qualKeys = industryOf(ctx.workspace.settings).qualification.slice(0, 3).map((q) => q.key);
  for (const c of cs) {
    const a = acts.filter((x) => x.c === c.id);
    const src = c.source ?? "";
    const resp = c.firstContactedAt ? (c.firstContactedAt.getTime() - c.createdAt.getTime()) / 60000 : 9999;
    const cf = c.customFields as Record<string, unknown>;
    out.set(c.id, [1, c.emails.length ? 1 : 0, c.phones.length ? 1 : 0, src.startsWith("meta") ? 1 : 0, src.startsWith("google") ? 1 : 0, src === "web_form" ? 1 : 0, ["whatsapp", "messenger"].includes(src) ? 1 : 0,
      !src || ["api", "import", "call"].includes(src) ? 1 : 0, resp <= 5 ? 1 : resp <= 60 ? 0.5 : 0, Math.min(a.reduce((s, x) => s + x.n, 0), 10) / 10, Math.min(inbound.find((x) => x.c === c.id)?.n ?? 0, 10) / 10,
      c.project ? 1 : 0, a.some((x) => x.t === "visit") ? 1 : 0, qualKeys.filter((k) => cf[k]).length / qualKeys.length]);
  }
  return out;
}

const sigmoid = (z: number) => 1 / (1 + Math.exp(-z));

/** Train a per-workspace logistic regression on won vs lost history; requires a minimum labelled history. */
export async function trainScoringModel(ctx: Ctx) {
  const MIN = Number(process.env.SCORING_MIN_LABELLED ?? 30);
  const closed = await ctx.db.select({ contactId: schema.deals.contactId, won: sql<boolean>`${schema.deals.wonAt} IS NOT NULL` }).from(schema.deals)
    .where(and(eq(schema.deals.workspaceId, ctx.workspace.id), or(isNotNull(schema.deals.wonAt), isNotNull(schema.deals.lostAt))));
  let weights: number[] | null = null;
  if (closed.length >= MIN && closed.some((c) => c.won) && closed.some((c) => !c.won)) {
    const feats = await featuresFor(ctx, closed.map((c) => c.contactId));
    const data = closed.map((c) => ({ x: feats.get(c.contactId)!, y: c.won ? 1 : 0 })).filter((d) => d.x);
    const pos = data.filter((d) => d.y).length, neg = data.length - pos;
    const wPos = data.length / (2 * pos), wNeg = data.length / (2 * neg); // class balancing
    weights = new Array(FEATURE_NAMES.length).fill(0);
    for (let epoch = 0; epoch < 400; epoch++) {
      const grad = new Array(weights.length).fill(0);
      for (const d of data) {
        const p = sigmoid(d.x.reduce((s, xi, i) => s + xi * weights![i]!, 0));
        const err = (p - d.y) * (d.y ? wPos : wNeg);
        d.x.forEach((xi, i) => (grad[i] += err * xi));
      }
      weights = weights.map((w, i) => w - (0.5 * (grad[i] / data.length) + 0.001 * w));
    }
  }
  const settings = { ...ctx.workspace.settings, scoringModel: weights ? { weights, trainedAt: new Date().toISOString(), samples: closed.length } : null } as typeof ctx.workspace.settings;
  await ctx.db.update(schema.workspaces).set({ settings }).where(eq(schema.workspaces.id, ctx.workspace.id));
  ctx.workspace.settings = settings;
  await scoreLeads(ctx);
  return { trained: !!weights, samples: closed.length, minimum: MIN };
}

/** Score 0–100 on every open lead with the trained model (or a transparent heuristic until enough history exists). */
export async function scoreLeads(ctx: Ctx, contactIds?: string[]) {
  const model = (ctx.workspace.settings as any)?.scoringModel as { weights: number[] } | null | undefined;
  const ids = contactIds ?? (await ctx.db.select({ id: schema.contacts.id }).from(schema.contacts).where(and(eq(schema.contacts.workspaceId, ctx.workspace.id), isNull(schema.contacts.deletedAt))).limit(20000)).map((r) => r.id);
  for (let i = 0; i < ids.length; i += 500) {
    const chunk = ids.slice(i, i + 500);
    const feats = await featuresFor(ctx, chunk);
    for (const [id, x] of feats) {
      let score: number, reason: string;
      if (model?.weights) {
        const contribs = x.map((xi, j) => ({ name: FEATURE_NAMES[j]!, v: xi * model.weights[j]! })).filter((c) => c.name !== "bias");
        score = Math.round(sigmoid(x.reduce((s, xi, j) => s + xi * model.weights[j]!, 0)) * 100);
        reason = `Model: ${contribs.sort((a, b) => Math.abs(b.v) - Math.abs(a.v)).slice(0, 3).map((c) => `${c.name.replace(/_/g, " ")} ${c.v >= 0 ? "+" : "−"}`).join(", ")}`;
      } else {
        const w = [10, 8, 10, 6, 6, 8, 10, 2, 14, 10, 8, 6, 18, 20];
        score = Math.min(100, Math.round(x.reduce((s, xi, j) => s + xi * w[j]!, 0)));
        reason = "Heuristic (not enough won/lost history to train yet)";
      }
      await ctx.db.update(schema.contacts).set({ score, scoreReason: reason }).where(eq(schema.contacts.id, id));
    }
  }
  return ids.length;
}

/* ---------------- AI-004 anomaly detection ---------------- */

export async function detectAnomalies(ctx: Ctx) {
  const threshold = ctx.workspace.settings?.anomalyThresholdPct ?? 40;
  const y = isoDay(-1);
  const since = isoDay(-8);
  const rows = await ctx.db.select({ cid: schema.campaigns.id, name: schema.campaigns.name, date: schema.adMetricsDaily.date, spend: sql<number>`sum(${schema.adMetricsDaily.spend})::bigint`, clicks: sql<number>`sum(${schema.adMetricsDaily.clicks})::int`, impressions: sql<number>`sum(${schema.adMetricsDaily.impressions})::int`, leads: sql<number>`sum(${schema.adMetricsDaily.leads})::int` })
    .from(schema.adMetricsDaily).innerJoin(schema.ads, eq(schema.ads.id, schema.adMetricsDaily.adId)).innerJoin(schema.adSets, eq(schema.adSets.id, schema.ads.adSetId)).innerJoin(schema.campaigns, eq(schema.campaigns.id, schema.adSets.campaignId))
    .where(and(eq(schema.adMetricsDaily.workspaceId, ctx.workspace.id), gte(schema.adMetricsDaily.date, since))).groupBy(schema.campaigns.id, schema.adMetricsDaily.date);
  const found: { metric: string; name: string; id: string; base: number; cur: number; pct: number }[] = [];
  const byCampaign = new Map<string, typeof rows>();
  for (const r of rows) byCampaign.set(r.cid, [...(byCampaign.get(r.cid) ?? []), r]);
  for (const [cid, rs] of byCampaign) {
    const today = rs.find((r) => r.date === y);
    const base = rs.filter((r) => r.date < y);
    if (!today || base.length < 3) continue;
    const avg = (f: (r: (typeof rs)[number]) => number | null) => { const v = base.map(f).filter((x): x is number => x !== null && Number.isFinite(x)); return v.length ? v.reduce((a, b) => a + b, 0) / v.length : null; };
    const metrics: [string, (r: (typeof rs)[number]) => number | null][] = [
      ["CPL", (r) => (r.leads ? Number(r.spend) / r.leads : null)], ["CTR", (r) => (r.impressions ? (r.clicks / r.impressions) * 100 : null)], ["Spend", (r) => Number(r.spend)], ["Leads", (r) => r.leads],
    ];
    for (const [m, f] of metrics) {
      const b = avg(f), c = f(today);
      if (b === null || c === null || b === 0) continue;
      const pct = ((c - b) / b) * 100;
      if (Math.abs(pct) >= threshold) found.push({ metric: m, name: today.name, id: cid, base: b, cur: c, pct });
    }
  }
  // lead volume across the workspace
  const lv = await ctx.db.select({ d: sql<string>`to_char(${schema.leadSources.capturedAt}, 'YYYY-MM-DD')`, n: sql<number>`count(*)::int` }).from(schema.leadSources).where(and(eq(schema.leadSources.workspaceId, ctx.workspace.id), gte(schema.leadSources.capturedAt, new Date(since)))).groupBy(sql`1`);
  const lvToday = lv.find((r) => r.d === y)?.n ?? 0, lvBase = lv.filter((r) => r.d < y);
  if (lvBase.length >= 3) {
    const b = lvBase.reduce((s, r) => s + r.n, 0) / lvBase.length;
    if (b > 0 && Math.abs(((lvToday - b) / b) * 100) >= threshold) found.push({ metric: "Lead volume", name: "All sources", id: "workspace", base: b, cur: lvToday, pct: ((lvToday - b) / b) * 100 });
  }
  const created = [];
  for (const a of found) {
    const fmt = (v: number) => (a.metric === "CPL" || a.metric === "Spend" ? formatMoney(v, ctx.workspace.currency) : a.metric === "CTR" ? `${v.toFixed(2)}%` : v.toFixed(0));
    const message = `${a.metric} ${a.pct > 0 ? "jumped" : "dropped"} ${Math.abs(a.pct).toFixed(0)}% on ${a.name} since yesterday (${fmt(a.base)} → ${fmt(a.cur)})`;
    const dup = await ctx.db.query.anomalies.findFirst({ where: and(eq(schema.anomalies.workspaceId, ctx.workspace.id), eq(schema.anomalies.message, message)) });
    if (dup) continue;
    const [row] = await ctx.db.insert(schema.anomalies).values({ workspaceId: ctx.workspace.id, metric: a.metric, objectType: a.id === "workspace" ? "workspace" : "campaign", objectId: a.id, objectName: a.name, baseline: a.base, current: a.cur, changePct: a.pct, message }).returning();
    created.push(row!);
    const { notifyAdmins } = await import("@/lib/services/notify");
    await notifyAdmins(ctx, "anomaly", "Anomaly detected", message, "/ads", ["workspace_admin", "marketing_manager", "performance"]);
  }
  return created;
}

/* ---------------- ADS-006 budget pacing ---------------- */

export async function checkPacing(ctx: Ctx) {
  const threshold = ctx.workspace.settings?.pacingThresholdPct ?? 15;
  const accounts = await ctx.db.select().from(schema.adAccounts).where(and(eq(schema.adAccounts.workspaceId, ctx.workspace.id), isNotNull(schema.adAccounts.monthlyBudget)));
  const now = new Date();
  const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
  const daysIn = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();
  const elapsed = Math.max(1, now.getUTCDate() - 1);
  const alerts = [];
  for (const a of accounts) {
    const [r] = await ctx.db.select({ s: sql<number>`COALESCE(sum(${schema.adMetricsDaily.spend}),0)::bigint` }).from(schema.adMetricsDaily).innerJoin(schema.ads, eq(schema.ads.id, schema.adMetricsDaily.adId)).innerJoin(schema.adSets, eq(schema.adSets.id, schema.ads.adSetId)).innerJoin(schema.campaigns, eq(schema.campaigns.id, schema.adSets.campaignId))
      .where(and(eq(schema.campaigns.adAccountId, a.id), gte(schema.adMetricsDaily.date, monthStart.toISOString().slice(0, 10))));
    const spent = Number(r?.s ?? 0);
    const projected = (spent / elapsed) * daysIn;
    const diff = a.monthlyBudget ? ((projected - a.monthlyBudget) / a.monthlyBudget) * 100 : 0;
    const status = Math.abs(diff) < threshold ? "on_track" : diff > 0 ? "over" : "under";
    alerts.push({ account: a, spent, projected, budget: a.monthlyBudget!, diffPct: diff, status });
    if (status !== "on_track" && now.getUTCDate() > 3) {
      const msg = `${a.name} projects ${formatMoney(projected, a.currency)} this month — ${Math.abs(diff).toFixed(0)}% ${status} the ${formatMoney(a.monthlyBudget, a.currency)} plan`;
      const dup = await ctx.db.query.anomalies.findFirst({ where: and(eq(schema.anomalies.workspaceId, ctx.workspace.id), eq(schema.anomalies.metric, "Pacing"), eq(schema.anomalies.objectId, a.id), gte(schema.anomalies.createdAt, new Date(Date.now() - 86400000))) });
      if (!dup) {
        await ctx.db.insert(schema.anomalies).values({ workspaceId: ctx.workspace.id, metric: "Pacing", objectType: "ad_account", objectId: a.id, objectName: a.name, baseline: a.monthlyBudget!, current: projected, changePct: diff, message: msg });
        const { notifyAdmins } = await import("@/lib/services/notify");
        await notifyAdmins(ctx, "pacing", "Budget pacing alert", msg, "/ads", ["workspace_admin", "marketing_manager", "performance"]);
      }
    }
  }
  return alerts;
}

/* ---------------- AI-005 ask-your-data ---------------- */

export const METRICS: Record<string, { label: string; definition: string }> = {
  leads: { label: "Leads", definition: "Distinct contacts with a lead source captured in the period" },
  qualified: { label: "Qualified leads", definition: "Deals created in the period that reached the Qualified stage or later" },
  site_visits: { label: "Visits / appointments", definition: "Visit activities (site visits, appointments, test drives…) logged in the period" },
  won: { label: "Won deals", definition: "Deals marked Won in the period" },
  revenue: { label: "Revenue", definition: "Sum of won deal values in the period" },
  spend: { label: "Ad spend", definition: "Sum of daily ad spend synced from ad platforms" },
  cpl: { label: "Cost per lead", definition: "Ad spend ÷ CRM leads attributed to ads in the period" },
  messages: { label: "Messages sent", definition: "Outbound messages across all channels" },
};
const DIMENSIONS = ["campaign", "adset", "source", "project", "rep", "day", "none"] as const;

export type AskPlan = { metric: keyof typeof METRICS; dimension: (typeof DIMENSIONS)[number]; from: string; to: string; limit: number; sort: "desc" | "asc"; explanation?: string };

export async function askData(ctx: Ctx, question: string) {
  const today = new Date().toISOString().slice(0, 10);
  let plan: AskPlan | null = null;
  let source = "ai";
  try {
    const { text } = await complete(ctx, {
      feature: "ask_your_data", tier: "fast",
      system: `Translate marketing questions into a query plan. Today is ${today}. Metrics: ${Object.entries(METRICS).map(([k, v]) => `${k} (${v.definition})`).join("; ")}. Dimensions: ${DIMENSIONS.join(", ")}. "last month" = the previous calendar month. Respond with JSON only: {"metric":"…","dimension":"…","from":"YYYY-MM-DD","to":"YYYY-MM-DD","limit":10,"sort":"desc","explanation":"one sentence"}`,
      messages: [{ role: "user", content: question }], maxTokens: 400,
    });
    plan = parseJson<AskPlan>(text);
  } catch (e) {
    if (!(e instanceof AiUnavailable)) throw e;
    source = "rules";
  }
  plan = sanitizePlan(plan ?? ruleBasedPlan(question));
  let rows = await runPlan(ctx, plan);
  if (["campaign", "adset"].includes(plan.dimension)) rows = rows.filter((r) => !r.label.startsWith("(no "));
  const m = METRICS[plan.metric]!;
  const top = rows[0];
  const answer = rows.length
    ? plan.dimension === "none" ? `${m.label}: ${fmtVal(ctx, plan.metric, top!.value)} between ${plan.from} and ${plan.to}.` : `${top!.label} had the ${plan.sort === "asc" ? "lowest" : "highest"} ${m.label.toLowerCase()} (${fmtVal(ctx, plan.metric, top!.value)}) between ${plan.from} and ${plan.to}.`
    : `No ${m.label.toLowerCase()} recorded between ${plan.from} and ${plan.to}.`;
  return { answer, plan, rows, metricDefinition: m.definition, query: describePlan(plan), source };
}

function fmtVal(ctx: Ctx, metric: string, v: number) {
  return ["revenue", "spend", "cpl"].includes(metric) ? formatMoney(v, ctx.workspace.currency) : String(Math.round(v * 100) / 100);
}

function sanitizePlan(p: AskPlan): AskPlan {
  const d = (s: string, fb: string) => (/^\d{4}-\d{2}-\d{2}$/.test(s ?? "") ? s : fb);
  return { metric: METRICS[p.metric] ? p.metric : "leads", dimension: DIMENSIONS.includes(p.dimension) ? p.dimension : "none", from: d(p.from, isoDay(-30)), to: d(p.to, isoDay(0)), limit: Math.min(Math.max(Number(p.limit) || 10, 1), 50), sort: p.sort === "asc" ? "asc" : "desc", explanation: p.explanation };
}

export function ruleBasedPlan(q: string): AskPlan {
  const s = q.toLowerCase();
  const metric = (/visit|appointment|test drive|meeting booked|consultation/.test(s) ? "site_visits" : /revenue|sales value/.test(s) ? "revenue" : /won|sale|booked|closed/.test(s) ? "won" : /qualif/.test(s) ? "qualified" : /cost per lead|cpl/.test(s) ? "cpl" : /spend|spent|budget/.test(s) ? "spend" : /message/.test(s) ? "messages" : "leads") as AskPlan["metric"];
  const dimension = (/ad ?set/.test(s) ? "adset" : /campaign/.test(s) ? "campaign" : /source|channel/.test(s) ? "source" : /project/.test(s) ? "project" : /rep|agent|sales ?person/.test(s) ? "rep" : /daily|per day|trend/.test(s) ? "day" : "none") as AskPlan["dimension"];
  const now = new Date();
  let from = isoDay(-30), to = isoDay(0);
  if (/last month/.test(s)) { const a = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1)); const b = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 0)); from = a.toISOString().slice(0, 10); to = b.toISOString().slice(0, 10); }
  else if (/this month/.test(s)) from = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString().slice(0, 10);
  else if (/last week|7 days/.test(s)) from = isoDay(-7);
  else if (/yesterday/.test(s)) { from = isoDay(-1); to = isoDay(-1); }
  else if (/today/.test(s)) from = isoDay(0);
  return { metric, dimension, from, to, limit: 10, sort: /least|lowest|worst/.test(s) ? "asc" : "desc", explanation: "Parsed with keyword rules (AI not configured)" };
}

function describePlan(p: AskPlan) {
  return `SELECT ${p.dimension === "none" ? "" : `${p.dimension}, `}${p.metric} FROM unified_data WHERE date BETWEEN '${p.from}' AND '${p.to}'${p.dimension === "none" ? "" : ` GROUP BY ${p.dimension} ORDER BY ${p.metric} ${p.sort.toUpperCase()} LIMIT ${p.limit}`}`;
}

async function runPlan(ctx: Ctx, p: AskPlan): Promise<{ label: string; value: number }[]> {
  const ws = ctx.workspace.id;
  const from = new Date(`${p.from}T00:00:00Z`), to = new Date(`${p.to}T23:59:59Z`);
  const ord = (rows: { label: string; value: number }[]) => rows.filter((r) => Number.isFinite(r.value)).sort((a, b) => (p.sort === "asc" ? a.value - b.value : b.value - a.value)).slice(0, p.limit);
  const users = new Map((await ctx.db.select({ id: schema.users.id, name: schema.users.name }).from(schema.users)).map((u) => [u.id, u.name]));
  const camps = await ctx.db.select({ e: schema.campaigns.externalId, n: schema.campaigns.name }).from(schema.campaigns).where(eq(schema.campaigns.workspaceId, ws));
  const sets = await ctx.db.select({ e: schema.adSets.externalId, n: schema.adSets.name }).from(schema.adSets).where(eq(schema.adSets.workspaceId, ws));
  const cName = new Map(camps.map((c) => [c.e, c.n])), sName = new Map(sets.map((c) => [c.e, c.n]));

  // contact-level attribution map for CRM metrics
  const src = await ctx.db.select({ c: schema.leadSources.contactId, channel: schema.leadSources.channel, campaign: schema.leadSources.campaignId, adset: schema.leadSources.adsetId, at: schema.leadSources.capturedAt }).from(schema.leadSources).where(eq(schema.leadSources.workspaceId, ws)).orderBy(asc(schema.leadSources.capturedAt));
  const firstSrc = new Map<string, (typeof src)[number]>();
  for (const s of src) if (!firstSrc.has(s.c)) firstSrc.set(s.c, s);
  const contacts = new Map((await ctx.db.select({ id: schema.contacts.id, project: schema.contacts.project, owner: schema.contacts.ownerId }).from(schema.contacts).where(eq(schema.contacts.workspaceId, ws))).map((c) => [c.id, c]));
  const keyFor = (contactId: string, at: Date, ownerId?: string | null): string => {
    const s = firstSrc.get(contactId);
    switch (p.dimension) {
      case "campaign": return s?.campaign ? cName.get(s.campaign) ?? s.campaign : "(no campaign)";
      case "adset": return s?.adset ? sName.get(s.adset) ?? s.adset : "(no ad set)";
      case "source": return s?.channel ?? "(unknown)";
      case "project": return contacts.get(contactId)?.project ?? "(no project)";
      case "rep": return users.get(ownerId ?? contacts.get(contactId)?.owner ?? "") ?? "(unassigned)";
      case "day": return at.toISOString().slice(0, 10);
      default: return "Total";
    }
  };
  const agg = (items: { contactId: string; at: Date; value: number; owner?: string | null }[]) => {
    const m = new Map<string, number>();
    for (const i of items) { const k = keyFor(i.contactId, i.at, i.owner); m.set(k, (m.get(k) ?? 0) + i.value); }
    return ord([...m].map(([label, value]) => ({ label, value })));
  };

  if (p.metric === "leads") {
    const seen = new Set<string>();
    return agg(src.filter((s) => s.at >= from && s.at <= to && !seen.has(s.c) && (seen.add(s.c), true)).map((s) => ({ contactId: s.c, at: s.at, value: 1 })));
  }
  if (p.metric === "site_visits") {
    const v = await ctx.db.select().from(schema.activities).where(and(eq(schema.activities.workspaceId, ws), eq(schema.activities.type, "visit"), gte(schema.activities.createdAt, from), sql`${schema.activities.createdAt} <= ${to}`));
    return agg(v.filter((a) => a.contactId).map((a) => ({ contactId: a.contactId!, at: a.createdAt, value: 1, owner: a.userId })));
  }
  if (p.metric === "won" || p.metric === "revenue") {
    const d = await ctx.db.select().from(schema.deals).where(and(eq(schema.deals.workspaceId, ws), gte(schema.deals.wonAt, from), sql`${schema.deals.wonAt} <= ${to}`));
    return agg(d.map((x) => ({ contactId: x.contactId, at: x.wonAt!, value: p.metric === "won" ? 1 : Number(x.value), owner: x.ownerId })));
  }
  if (p.metric === "qualified") {
    const { funnel } = await import("@/lib/services/analytics");
    if (p.dimension === "none") { const f = await funnel(ctx, { from, to }); return [{ label: "Total", value: f?.stages[1]?.count ?? 0 }]; }
    const pipeline = (await ctx.db.select().from(schema.pipelines).where(eq(schema.pipelines.workspaceId, ws)).limit(1))[0];
    const qOrder = pipeline?.stages.find((s) => /qualif/i.test(s.name))?.order ?? 2;
    const order = new Map(pipeline?.stages.map((s) => [s.id, s.order]) ?? []);
    const d = await ctx.db.select().from(schema.deals).where(and(eq(schema.deals.workspaceId, ws), gte(schema.deals.createdAt, from), sql`${schema.deals.createdAt} <= ${to}`));
    return agg(d.filter((x) => x.wonAt || (order.get(x.stageId) ?? 0) >= qOrder).map((x) => ({ contactId: x.contactId, at: x.createdAt, value: 1, owner: x.ownerId })));
  }
  if (p.metric === "messages") {
    const m = await ctx.db.select({ c: schema.conversations.contactId, at: schema.messages.createdAt, ch: schema.messages.channel }).from(schema.messages).innerJoin(schema.conversations, eq(schema.conversations.id, schema.messages.conversationId)).where(and(eq(schema.messages.workspaceId, ws), eq(schema.messages.direction, "out"), gte(schema.messages.createdAt, from), sql`${schema.messages.createdAt} <= ${to}`));
    if (p.dimension === "source") { const mm = new Map<string, number>(); m.forEach((x) => mm.set(x.ch, (mm.get(x.ch) ?? 0) + 1)); return ord([...mm].map(([label, value]) => ({ label, value }))); }
    return agg(m.map((x) => ({ contactId: x.c, at: x.at, value: 1 })));
  }
  // ad metrics
  const rows = await ctx.db.select({ date: schema.adMetricsDaily.date, spend: schema.adMetricsDaily.spend, campaign: schema.campaigns.name, cExt: schema.campaigns.externalId, adset: schema.adSets.name, provider: schema.ads.provider })
    .from(schema.adMetricsDaily).innerJoin(schema.ads, eq(schema.ads.id, schema.adMetricsDaily.adId)).innerJoin(schema.adSets, eq(schema.adSets.id, schema.ads.adSetId)).innerJoin(schema.campaigns, eq(schema.campaigns.id, schema.adSets.campaignId))
    .where(and(eq(schema.adMetricsDaily.workspaceId, ws), gte(schema.adMetricsDaily.date, p.from), sql`${schema.adMetricsDaily.date} <= ${p.to}`));
  const key = (r: (typeof rows)[number]) => (p.dimension === "campaign" ? r.campaign : p.dimension === "adset" ? r.adset : p.dimension === "source" ? r.provider : p.dimension === "day" ? r.date : "Total");
  const spend = new Map<string, number>();
  for (const r of rows) spend.set(key(r), (spend.get(key(r)) ?? 0) + Number(r.spend));
  if (p.metric === "spend") return ord([...spend].map(([label, value]) => ({ label, value })));
  // cpl
  const leads = new Map<string, number>();
  const seen = new Set<string>();
  for (const s of src) {
    if (s.at < from || s.at > to || seen.has(s.c) || !s.campaign) continue;
    seen.add(s.c);
    const k = p.dimension === "campaign" ? cName.get(s.campaign) ?? s.campaign : p.dimension === "adset" ? (s.adset ? sName.get(s.adset) ?? s.adset : "(no ad set)") : p.dimension === "source" ? (s.channel.startsWith("google") ? "google" : s.channel.startsWith("meta") ? "meta" : s.channel) : p.dimension === "day" ? s.at.toISOString().slice(0, 10) : "Total";
    leads.set(k, (leads.get(k) ?? 0) + 1);
  }
  return ord([...spend].filter(([k]) => leads.get(k)).map(([label, v]) => ({ label, value: v / leads.get(label)! })));
}

/* ---------------- AI-006 recommendations ---------------- */

export async function budgetRecommendations(ctx: Ctx) {
  const { campaignPerformance } = await import("@/lib/services/analytics");
  const perf = (await campaignPerformance(ctx, { from: new Date(Date.now() - 14 * 86400000), to: new Date() })).filter((c) => c.spend > 0 && c.status === "active");
  if (perf.length < 2) return [];
  const withQ = perf.filter((c) => c.cpql !== null);
  const avg = withQ.reduce((s, c) => s + c.cpql!, 0) / Math.max(withQ.length, 1);
  const recs: { campaignId: string; name: string; provider: string; action: "scale" | "reduce" | "pause"; changePct: number; reasoning: string; expectedImpact: string }[] = [];
  for (const c of perf) {
    if (c.cpql === null && c.spend > avg * 2 && c.leads > 0) recs.push({ campaignId: c.campaignId, name: c.name, provider: c.provider, action: "pause", changePct: -100, reasoning: `Spent ${formatMoney(c.spend, ctx.workspace.currency)} in 14 days with ${c.leads} leads and zero qualified.`, expectedImpact: `Frees ~${formatMoney(c.spend / 2, ctx.workspace.currency)}/week for better campaigns.` });
    else if (c.cpql !== null && c.cpql < avg * 0.7) recs.push({ campaignId: c.campaignId, name: c.name, provider: c.provider, action: "scale", changePct: 20, reasoning: `Cost per qualified lead ${formatMoney(c.cpql, ctx.workspace.currency)} is ${Math.round((1 - c.cpql / avg) * 100)}% below the account average (${formatMoney(avg, ctx.workspace.currency)}).`, expectedImpact: `+${Math.max(1, Math.round((c.qualified * 0.2) / 2))} qualified leads / week at similar efficiency.` });
    else if (c.cpql !== null && c.cpql > avg * 1.5) recs.push({ campaignId: c.campaignId, name: c.name, provider: c.provider, action: "reduce", changePct: -25, reasoning: `Cost per qualified lead ${formatMoney(c.cpql, ctx.workspace.currency)} is ${Math.round((c.cpql / avg - 1) * 100)}% above average.`, expectedImpact: `Saves ~${formatMoney(c.spend * 0.25 / 2, ctx.workspace.currency)}/week; reallocate to scaling campaigns.` });
  }
  return recs;
}

export async function nextBestAction(ctx: Ctx, contactId: string) {
  const c = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contactId) }))!;
  const deal = await ctx.db.query.deals.findFirst({ where: and(eq(schema.deals.contactId, contactId), isNull(schema.deals.wonAt), isNull(schema.deals.lostAt)) });
  const pipeline = deal ? await ctx.db.query.pipelines.findFirst({ where: eq(schema.pipelines.id, deal.pipelineId) }) : null;
  const stage = pipeline?.stages.find((s) => s.id === deal?.stageId);
  const openTasks = await ctx.db.select().from(schema.activities).where(and(eq(schema.activities.contactId, contactId), isNull(schema.activities.completedAt), isNotNull(schema.activities.dueAt)));
  const lastIn = await ctx.db.select({ at: schema.messages.createdAt, ch: schema.messages.channel }).from(schema.messages).innerJoin(schema.conversations, eq(schema.conversations.id, schema.messages.conversationId)).where(and(eq(schema.conversations.contactId, contactId), eq(schema.messages.direction, "in"))).orderBy(desc(schema.messages.createdAt)).limit(1);
  const cf = c.customFields as Record<string, unknown>;
  const idleDays = c.lastActivityAt ? (Date.now() - c.lastActivityAt.getTime()) / 86400000 : 99;
  if (!c.firstContactedAt) return { action: "Call now", reasoning: "Lead has not been contacted yet; response within 5 minutes converts far better.", expectedImpact: "Highest-leverage step for this lead", channel: "call" };
  if (lastIn[0] && Date.now() - lastIn[0].at.getTime() < 24 * 3600000) return { action: `Reply on ${lastIn[0].ch}`, reasoning: "Lead messaged in the last 24 hours and the session window is open.", expectedImpact: "Keeps momentum; free-form replies allowed", channel: lastIn[0].ch };
  const ind = industryOf(ctx.workspace.settings);
  const missing = ind.qualification.slice(0, 3).filter((q) => !cf[q.key]);
  if (missing.length) return { action: `Qualify: ask ${missing.map((q) => q.label.toLowerCase()).join(", ")}`, reasoning: `Missing ${missing.map((q) => q.label.toLowerCase()).join(", ")}.`, expectedImpact: "Moves the lead toward Qualified and improves CAPI signal", channel: "whatsapp" };
  if (stage && (stage.id === "qualified" || stage.conversionEvent === "Qualified" || /qualif/i.test(stage.name))) return { action: `Book a ${ind.visit.toLowerCase()}`, reasoning: `Lead is qualified but no ${ind.visit.toLowerCase()} is booked.`, expectedImpact: `${ind.visitPlural} are a strong predictor of a sale`, channel: "call" };
  if (openTasks.some((t) => t.dueAt! < new Date())) return { action: "Complete overdue task", reasoning: `${openTasks.filter((t) => t.dueAt! < new Date()).length} task(s) overdue.`, expectedImpact: "Prevents the lead going cold", channel: "task" };
  if (idleDays > 7) return { action: "Re-engage with a WhatsApp template", reasoning: `No activity for ${Math.round(idleDays)} days.`, expectedImpact: "Re-engagement flows recover a share of cold leads", channel: "whatsapp" };
  return { action: "Follow up on negotiation", reasoning: `Deal is at ${stage?.name ?? "an open stage"}.`, expectedImpact: "Keep the deal progressing", channel: "call" };
}

/* ---------------- AI-007 summaries ---------------- */

export async function summarizeConversation(ctx: Ctx, conversationId: string) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw new ApiError(404, "not_found", "Conversation not found");
  const msgs = await ctx.db.select().from(schema.messages).where(eq(schema.messages.conversationId, conv.id)).orderBy(asc(schema.messages.createdAt)).limit(200);
  const transcript = msgs.map((m) => `${m.direction === "in" ? "Lead" : m.direction === "note" ? "Note" : "Agent"}: ${m.body}`).join("\n");
  return summarizeAndLog(ctx, conv.contactId, `${conv.channel} conversation`, transcript);
}

export async function summarizeActivity(ctx: Ctx, activityId: string) {
  const a = await ctx.db.query.activities.findFirst({ where: eq(schema.activities.id, activityId) });
  if (!a?.contactId) return null;
  const transcript = [a.body, a.outcome ? `Outcome: ${a.outcome}` : "", a.recordingUrl ? `Recording: ${a.recordingUrl}` : ""].filter(Boolean).join("\n");
  if (!transcript.trim()) return null;
  return summarizeAndLog(ctx, a.contactId, `${a.type} "${a.title}"`, transcript);
}

async function summarizeAndLog(ctx: Ctx, contactId: string, label: string, transcript: string) {
  const { text } = await complete(ctx, {
    feature: "summarize", tier: "fast",
    system: "Summarize sales conversations for a CRM. Respond with JSON only: {\"summary\":\"2-3 sentences\",\"next_steps\":[\"…\"],\"sentiment\":\"positive|neutral|negative\",\"fields\":{\"budget\":\"\",\"location\":\"\",\"timeline\":\"\"}}. Leave unknown fields empty. Keep the language of the transcript for the summary.",
    messages: [{ role: "user", content: `Transcript of ${label}:\n${transcript.slice(0, 30000)}` }], maxTokens: 1200,
  });
  const s = parseJson<{ summary: string; next_steps: string[]; sentiment: string; fields?: Record<string, string> }>(text) ?? { summary: text, next_steps: [], sentiment: "neutral" };
  const [act] = await ctx.db.insert(schema.activities).values({ workspaceId: ctx.workspace.id, contactId, type: "ai_summary", title: `AI summary · ${label}`, body: `${s.summary}${s.next_steps?.length ? `\n\nNext steps:\n${s.next_steps.map((x) => `• ${x}`).join("\n")}` : ""}`, outcome: s.sentiment, completedAt: new Date() }).returning();
  const fields = Object.fromEntries(Object.entries(s.fields ?? {}).filter(([, v]) => v));
  if (Object.keys(fields).length) {
    const c = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contactId) }))!;
    const missing = Object.fromEntries(Object.entries(fields).filter(([k]) => !(c.customFields as Record<string, unknown>)[k]));
    if (Object.keys(missing).length) await ctx.db.update(schema.contacts).set({ customFields: { ...c.customFields, ...missing } }).where(eq(schema.contacts.id, contactId));
  }
  return { ...s, activityId: act!.id };
}

/* ---------------- AI-008 agent actions & approval queue ---------------- */

export async function proposeAction(ctx: Ctx, input: { agent: string; kind: string; proposedAction: Record<string, unknown>; reasoning: string; expectedImpact: string }) {
  const [a] = await ctx.db.insert(schema.aiActions).values({ workspaceId: ctx.workspace.id, ...input, createdBy: ctx.user?.id ?? null }).returning();
  await audit(ctx, "ai.propose", "ai_action", a!.id, undefined, input);
  await emit(ctx.db, ctx.workspace.id, "ai.action_proposed", { action_id: a!.id, kind: input.kind, proposed: input.proposedAction });
  // explicit auto-approve rules with limits (AI-008 acceptance)
  const rule = await ctx.db.query.aiAutoApproveRules.findFirst({ where: and(eq(schema.aiAutoApproveRules.workspaceId, ctx.workspace.id), eq(schema.aiAutoApproveRules.kind, input.kind), eq(schema.aiAutoApproveRules.active, true)) });
  const pct = Math.abs(Number(input.proposedAction.changePct ?? 0));
  if (rule && (input.kind !== "change_budget" || pct <= rule.maxBudgetChangePct)) {
    return executeAction(ctx, a!.id, { auto: true });
  }
  const { notifyAdmins } = await import("@/lib/services/notify");
  await notifyAdmins(ctx, "approval", `Approval needed: ${input.kind.replace(/_/g, " ")}`, input.reasoning, "/ai/approvals", ["workspace_admin", "marketing_manager"]);
  return a!;
}

export async function decideAction(ctx: Ctx, id: string, decision: "approve" | "reject", edits?: { text?: string }) {
  // matrix: admins & marketing managers approve (A); performance marketers may only propose (C)
  const a = await ctx.db.query.aiActions.findFirst({ where: and(eq(schema.aiActions.id, id), eq(schema.aiActions.workspaceId, ctx.workspace.id)) });
  if (!a) throw new ApiError(404, "not_found", "Action not found");
  // social replies are approved by whoever may reply on social (social.reply); spend actions need ai_spend A
  if (a.kind === "social_reply" ? !(ctx.perms.social === "C" || ctx.perms.social_ai === "C") : ctx.perms.ai_spend !== "A") throw new ApiError(403, "forbidden", a.kind === "social_reply" ? "You need social reply permission to approve AI replies" : "Only admins and marketing managers can approve AI spend actions");
  if (a.status !== "proposed") throw new ApiError(409, "conflict", `Action already ${a.status}`);
  if (decision === "reject") {
    const [r] = await ctx.db.update(schema.aiActions).set({ status: "rejected", approverId: ctx.user?.id ?? null, updatedAt: new Date() }).where(eq(schema.aiActions.id, id)).returning();
    await audit(ctx, "ai.reject", "ai_action", id, a, r);
    return r!;
  }
  await ctx.db.update(schema.aiActions).set({ status: "approved", approverId: ctx.user?.id ?? null, updatedAt: new Date(), ...(edits?.text && a.kind === "social_reply" ? { proposedAction: { ...a.proposedAction, text: edits.text, editedByHuman: true } } : {}) }).where(eq(schema.aiActions.id, id));
  return executeAction(ctx, id, { auto: false });
}

/** Every write is logged with user or agent, before and after values (ADS-008). */
async function executeAction(ctx: Ctx, id: string, opts: { auto: boolean }) {
  const a = (await ctx.db.query.aiActions.findFirst({ where: eq(schema.aiActions.id, id) }))!;
  const p = a.proposedAction as Record<string, any>;
  const { pushVia } = await import("@/connectors");
  try {
    let before: unknown = null, after: unknown = null;
    if (a.kind === "pause_ad" || a.kind === "resume_ad" || a.kind === "change_budget") {
      const camp = await ctx.db.query.campaigns.findFirst({ where: and(eq(schema.campaigns.id, p.campaignId), eq(schema.campaigns.workspaceId, ctx.workspace.id)) });
      if (!camp) throw new Error("Campaign not found");
      const account = await ctx.db.query.adAccounts.findFirst({ where: eq(schema.adAccounts.id, camp.adAccountId) });
      const integration = account?.integrationId ? await ctx.db.query.integrations.findFirst({ where: eq(schema.integrations.id, account.integrationId) }) : null;
      if (!integration) throw new Error("Ad account integration not connected");
      before = { status: camp.status, budget: camp.budget };
      if (a.kind === "change_budget") {
        const newBudget = Math.round((camp.budget ?? 0) * (1 + Number(p.changePct) / 100));
        await pushVia(ctx, integration, "ad.budget", { externalId: camp.externalId, budget: newBudget });
        await ctx.db.update(schema.campaigns).set({ budget: newBudget, updatedAt: new Date() }).where(eq(schema.campaigns.id, camp.id));
        after = { status: camp.status, budget: newBudget };
      } else {
        const status = a.kind === "pause_ad" ? "paused" : "active";
        await pushVia(ctx, integration, "ad.status", { externalId: camp.externalId, status });
        await ctx.db.update(schema.campaigns).set({ status, updatedAt: new Date() }).where(eq(schema.campaigns.id, camp.id));
        after = { status, budget: camp.budget };
      }
      await audit({ ...ctx, actor: opts.auto ? { type: "agent", id: a.agent, name: `${a.agent} (auto-approved)` } : ctx.actor }, `ads.${a.kind}`, "campaign", camp.id, before, after);
    } else if (a.kind === "launch_journey") {
      const { publishJourney } = await import("@/lib/services/journeys");
      const j = await publishJourney(ctx, p.journeyId);
      after = { status: j.status, version: j.version };
    } else if (a.kind === "social_reply") {
      const { executeSocialReply } = await import("./social");
      await executeSocialReply(ctx, p as { conversationId: string; commentId?: string; reviewId?: string; text: string });
      after = { sent: p.text, edited: !!p.editedByHuman };
    } else throw new Error(`Unsupported action ${a.kind}`);
    const [r] = await ctx.db.update(schema.aiActions).set({ status: "executed", result: { before, after, auto: opts.auto }, updatedAt: new Date() }).where(eq(schema.aiActions.id, id)).returning();
    await emit(ctx.db, ctx.workspace.id, "ai.action_executed", { action_id: id, kind: a.kind, before, after });
    return r!;
  } catch (e) {
    const [r] = await ctx.db.update(schema.aiActions).set({ status: "failed", result: { error: (e as Error).message }, updatedAt: new Date() }).where(eq(schema.aiActions.id, id)).returning();
    return r!;
  }
}

export { aiConfigured };
