/**
 * In-app AI assistant (text + voice). A Claude tool-use loop over the platform's own services, run through the gateway
 * (credits, logging, refusal fallback). It can answer "how do I…" questions, look things up and do work:
 * search contacts, create leads and tasks, pull metrics, answer data questions and navigate.
 * Anything outbound or hard to undo (sending a message, moving a deal) is returned as a signed pending action that the
 * user must confirm — the model never executes those directly. Every tool runs with the signed-in user's permissions.
 */
import type Anthropic from "@anthropic-ai/sdk";
import { and, desc, eq, ilike, isNull, or, sql } from "drizzle-orm";
import { SignJWT, jwtVerify } from "jose";
import { z } from "zod";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { ApiError } from "@/lib/api";
import { audit } from "@/lib/audit";
import { formatMoneyShort, fullName } from "@/lib/util";
import { industryOf } from "@/lib/industry";
import { PLANS_CATALOG, normalizePlan } from "@/lib/plans";
import { aiConfigured, complete } from "./gateway";

export type ClientAction = { type: "navigate"; href: string; label: string } | { type: "confirm"; token: string; title: string; detail: string };
export type AssistantReply = { reply: string; actions: ClientAction[]; tools: string[]; source: "ai" | "guide" };

const secret = () => new TextEncoder().encode(process.env.AUTH_SECRET ?? "tempest-pulse-dev-secret-change-me");

/** Pages the assistant may open (keeps navigation inside the app). */
const PAGES: Record<string, string> = {
  dashboard: "/dashboard", contacts: "/contacts", "new lead": "/contacts?new=1", import: "/contacts/import", pipeline: "/pipeline", deals: "/pipeline", tasks: "/tasks", segments: "/segments",
  inbox: "/inbox", journeys: "/journeys", broadcasts: "/broadcasts", templates: "/templates", ads: "/ads", campaigns: "/ads", content: "/content", forms: "/forms",
  analytics: "/analytics", reports: "/reports", "ai studio": "/ai", approvals: "/ai/approvals", integrations: "/integrations", settings: "/settings",
  billing: "/settings/billing", plans: "/settings/billing", security: "/settings/security", "two-factor": "/settings/security", team: "/settings/team", "security policy": "/settings/security-policy",
  "social inbox settings": "/settings/social", "engagement rules": "/inbox/rules", "knowledge base": "/inbox/knowledge", pipelines: "/settings/pipelines", fields: "/settings/fields", "api keys": "/settings/api",
};

/** Compact product guide — the stable, cacheable part of the system prompt. */
const GUIDE = `PRODUCT GUIDE (answer "how do I…" questions from this; name the page and the steps):
- Add a lead: Accounts/Contacts → "New lead", or Pipeline → "New deal". Import a CSV/XLSX: Contacts → Import (maps columns, dedupes by phone/email).
- Pipeline: drag deals between stages; Won needs a value, Lost needs a reason. Stage names follow the workspace industry and can be edited in Settings → Pipelines & routing.
- Inbox: WhatsApp, Messenger, Instagram, SMS, email, Facebook/Instagram comments, YouTube and Google reviews in one place; assign, snooze, notes with @mentions, saved replies with "/".
- Journeys: visual automations (triggers, waits, messages, branches, A/B tests). Broadcasts send a template to a segment with throttling and quiet hours.
- Ads: connect Meta/Google/TikTok/LinkedIn in Integrations; CRM stages send conversions back (Conversions API).
- Reports: build a client report, share a link or schedule a PDF email. Analytics shows funnel, cost per stage and attribution.
- Social inbox: Settings → Social inbox to connect pages; Inbox → Engagement rules for auto-replies and moderation; Knowledge base grounds AI replies.
- Security: Profile & security → add a passkey, authenticator app, SMS or email code, backup codes; admins use Security policy to require 2FA, allowed methods, IP allowlist.
- Industry: Settings → General → Industry switches the funnel, lead fields, AI questions and labels. Dashboard → "Customize dashboard" to show/hide/reorder widgets.
- Plans: Starter $50 (3 seats, CRM, inbox, forms, AI help), Growth $100 (10 seats, journeys, broadcasts, social inbox, ads, attribution, voice AI), Enterprise $250 (50 seats, agency/white-label, API & webhooks, custom roles, AI autopilot). Change in Settings → Plan & billing.
- Forgot password: sign-in page → "Forgot password?" sends a code by email or SMS.`;

const TOOLS: Anthropic.Tool[] = [
  { name: "search_contacts", description: "Find contacts/leads by name, phone or email. Returns up to 8 matches with id, name, phone, email, lifecycle stage and owner.", input_schema: { type: "object", properties: { query: { type: "string", description: "Name, phone or email fragment" } }, required: ["query"], additionalProperties: false } },
  { name: "get_contact", description: "Full details for one contact: fields, open deals with stage and value, and the latest activities.", input_schema: { type: "object", properties: { contact_id: { type: "string" } }, required: ["contact_id"], additionalProperties: false } },
  { name: "create_lead", description: "Create a new lead (contact + deal) in the CRM. Use when the user asks to add a lead/customer. At least a phone or email is needed.", input_schema: { type: "object", properties: { name: { type: "string" }, phone: { type: "string" }, email: { type: "string" }, interest: { type: "string", description: "Product/project/service they want" }, note: { type: "string" } }, required: ["name"], additionalProperties: false } },
  { name: "create_task", description: "Create a task, call, meeting or visit/appointment, optionally linked to a contact and with a due date-time (ISO 8601 in the workspace timezone).", input_schema: { type: "object", properties: { title: { type: "string" }, type: { type: "string", enum: ["task", "call", "meeting", "visit"] }, contact_id: { type: "string" }, due_iso: { type: "string" } }, required: ["title", "type"], additionalProperties: false } },
  { name: "get_metrics", description: "Headline numbers for the last N days: new leads, revenue won, deals won, open pipeline value, win rate, median first response.", input_schema: { type: "object", properties: { days: { type: "integer", minimum: 1, maximum: 365 } }, required: ["days"], additionalProperties: false } },
  { name: "ask_data", description: "Answer an analytical question about leads, spend, CPL, revenue, won deals, visits or messages by source/campaign/rep/day.", input_schema: { type: "object", properties: { question: { type: "string" } }, required: ["question"], additionalProperties: false } },
  { name: "list_open_conversations", description: "Open inbox conversations needing attention (unanswered first) with the latest message.", input_schema: { type: "object", properties: { limit: { type: "integer", minimum: 1, maximum: 15 } }, required: ["limit"], additionalProperties: false } },
  { name: "list_tasks_due", description: "The signed-in user's open tasks due today or overdue.", input_schema: { type: "object", properties: {}, additionalProperties: false } },
  { name: "send_message", description: "Prepare a WhatsApp/SMS/email/Messenger message to a contact. The user must confirm before it is sent — say so.", input_schema: { type: "object", properties: { contact_id: { type: "string" }, channel: { type: "string", enum: ["whatsapp", "sms", "email", "messenger", "instagram"] }, body: { type: "string" }, subject: { type: "string" } }, required: ["contact_id", "channel", "body"], additionalProperties: false } },
  { name: "move_deal_stage", description: "Prepare moving a deal to another pipeline stage (by stage name). The user must confirm — say so.", input_schema: { type: "object", properties: { deal_id: { type: "string" }, stage_name: { type: "string" } }, required: ["deal_id", "stage_name"], additionalProperties: false } },
  { name: "navigate", description: `Open a page for the user. page must be one of: ${Object.keys(PAGES).join(", ")}.`, input_schema: { type: "object", properties: { page: { type: "string" }, reason: { type: "string" } }, required: ["page"], additionalProperties: false } },
];

const INPUTS = {
  search_contacts: z.object({ query: z.string().min(1).max(120) }),
  get_contact: z.object({ contact_id: z.string().uuid() }),
  create_lead: z.object({ name: z.string().min(1).max(120), phone: z.string().max(30).optional(), email: z.string().email().max(200).optional(), interest: z.string().max(120).optional(), note: z.string().max(1000).optional() }),
  create_task: z.object({ title: z.string().min(1).max(200), type: z.enum(["task", "call", "meeting", "visit"]), contact_id: z.string().uuid().optional(), due_iso: z.string().max(40).optional() }),
  get_metrics: z.object({ days: z.number().int().min(1).max(365) }),
  ask_data: z.object({ question: z.string().min(3).max(300) }),
  list_open_conversations: z.object({ limit: z.number().int().min(1).max(15) }),
  list_tasks_due: z.object({}),
  send_message: z.object({ contact_id: z.string().uuid(), channel: z.enum(["whatsapp", "sms", "email", "messenger", "instagram"]), body: z.string().min(1).max(4000), subject: z.string().max(200).optional() }),
  move_deal_stage: z.object({ deal_id: z.string().uuid(), stage_name: z.string().min(1).max(80) }),
  navigate: z.object({ page: z.string().max(60), reason: z.string().max(200).optional() }),
} as const;

async function pending(ctx: Ctx, kind: string, args: Record<string, unknown>) {
  return new SignJWT({ kind, args, uid: ctx.user?.id, ws: ctx.workspace.id }).setProtectedHeader({ alg: "HS256" }).setExpirationTime("10m").sign(secret());
}

async function runTool(ctx: Ctx, name: string, raw: unknown, actions: ClientAction[]): Promise<string> {
  const schemaFor = INPUTS[name as keyof typeof INPUTS];
  if (!schemaFor) throw new Error(`Unknown tool ${name}`);
  const input = schemaFor.parse(raw) as Record<string, any>;
  const ws = ctx.workspace;
  switch (name) {
    case "search_contacts": {
      const q = `%${input.query.trim()}%`;
      const own = ctx.perms.contacts === "C:assigned" || ctx.perms.contacts === "V:own" ? ctx.user?.id : null;
      const rows = await ctx.db.select().from(schema.contacts).where(and(eq(schema.contacts.workspaceId, ws.id), isNull(schema.contacts.deletedAt), own ? eq(schema.contacts.ownerId, own) : undefined,
        or(ilike(schema.contacts.firstName, q), ilike(schema.contacts.lastName, q), sql`array_to_string(${schema.contacts.phones}, ' ') ILIKE ${q}`, sql`array_to_string(${schema.contacts.emails}, ' ') ILIKE ${q}`))).limit(8);
      return JSON.stringify(rows.map((c) => ({ id: c.id, name: fullName(c), phone: c.phones[0] ?? null, email: c.emails[0] ?? null, stage: c.lifecycleStage, interest: c.project, score: c.score })));
    }
    case "get_contact": {
      const { getContact } = await import("@/lib/services/contacts");
      const c = await getContact(ctx, input.contact_id);
      const deals = await ctx.db.select().from(schema.deals).where(and(eq(schema.deals.contactId, c.id), eq(schema.deals.workspaceId, ws.id))).limit(5);
      const pl = deals[0] ? await ctx.db.query.pipelines.findFirst({ where: eq(schema.pipelines.id, deals[0].pipelineId) }) : null;
      const acts = await ctx.db.select().from(schema.activities).where(eq(schema.activities.contactId, c.id)).orderBy(desc(schema.activities.createdAt)).limit(5);
      return JSON.stringify({ id: c.id, name: fullName(c), phones: c.phones, emails: c.emails, stage: c.lifecycleStage, interest: c.project, fields: c.customFields, score: c.score,
        deals: deals.map((d) => ({ id: d.id, title: d.title, stage: pl?.stages.find((s) => s.id === d.stageId)?.name ?? d.stageId, value: formatMoneyShort(Number(d.value), d.currency), won: !!d.wonAt, lost: !!d.lostAt })),
        recent_activity: acts.map((a) => ({ type: a.type, title: a.title, due: a.dueAt, done: !!a.completedAt })) });
    }
    case "create_lead": {
      if (!input.phone && !input.email) return JSON.stringify({ error: "Ask the user for a phone number or email before creating the lead." });
      const { captureLead } = await import("@/lib/services/leads");
      const r = await captureLead({ ...ctx, actor: { type: "agent", id: "assistant", name: `AI assistant for ${ctx.actor.name}` } }, { name: input.name, phone: input.phone, email: input.email, project: input.interest, note: input.note, attribution: { channel: "manual" } });
      actions.push({ type: "navigate", href: `/contacts/${r.contact.id}`, label: `Open ${fullName(r.contact)}` });
      return JSON.stringify({ created: !r.duplicate, duplicate: r.duplicate, contact_id: r.contact.id, deal_id: r.deal?.id ?? null });
    }
    case "create_task": {
      const { createActivity } = await import("@/lib/services/leads");
      const due = input.due_iso ? new Date(input.due_iso) : null;
      if (due && Number.isNaN(due.getTime())) return JSON.stringify({ error: "Invalid due date — ask for a specific day and time." });
      const a = await createActivity(ctx, { contactId: input.contact_id ?? null, type: input.type, title: input.title, dueAt: due });
      actions.push({ type: "navigate", href: "/tasks", label: "Open tasks" });
      return JSON.stringify({ created: true, task_id: a.id, due: due?.toISOString() ?? null });
    }
    case "get_metrics": {
      const { kpis } = await import("@/lib/services/analytics");
      const to = new Date(), from = new Date(Date.now() - input.days * 86400000);
      const k = await kpis(ctx, { from, to });
      const D = schema.deals;
      const [w] = await ctx.db.select({ n: sql<number>`count(*) FILTER (WHERE ${D.wonAt} BETWEEN ${from} AND ${to})::int`, v: sql<number>`coalesce(sum(${D.value}) FILTER (WHERE ${D.wonAt} BETWEEN ${from} AND ${to}),0)::bigint`, lost: sql<number>`count(*) FILTER (WHERE ${D.lostAt} BETWEEN ${from} AND ${to})::int`, open: sql<number>`coalesce(sum(${D.value}) FILTER (WHERE ${D.wonAt} IS NULL AND ${D.lostAt} IS NULL),0)::bigint` }).from(D).where(eq(D.workspaceId, ws.id));
      return JSON.stringify({ period_days: input.days, new_leads: k.newLeads, deals_won: w?.n ?? 0, revenue_won: formatMoneyShort(Number(w?.v ?? 0), ws.currency), open_pipeline: formatMoneyShort(Number(w?.open ?? 0), ws.currency), win_rate_pct: w && w.n + w.lost ? Math.round((w.n / (w.n + w.lost)) * 100) : null, median_first_response_min: k.medianResponseMin });
    }
    case "ask_data": {
      const { askData } = await import("./features");
      const r = await askData(ctx, input.question);
      return JSON.stringify({ answer: r.answer, metric_definition: r.metricDefinition, rows: r.rows?.slice(0, 10) });
    }
    case "list_open_conversations": {
      const C = schema.conversations;
      const rows = await ctx.db.select({ c: C, contact: { firstName: schema.contacts.firstName, lastName: schema.contacts.lastName } }).from(C).innerJoin(schema.contacts, eq(schema.contacts.id, C.contactId))
        .where(and(eq(C.workspaceId, ws.id), sql`${C.status} IN ('open','pending')`, ctx.perms.messaging === "C:assigned" ? eq(C.assigneeId, ctx.user?.id ?? "") : undefined)).orderBy(sql`(${C.firstResponseAt} IS NULL) DESC`, desc(C.lastMessageAt)).limit(input.limit);
      return JSON.stringify(rows.map(({ c, contact }) => ({ id: c.id, contact: fullName(contact as never), channel: c.channel, kind: c.kind, unanswered: !c.firstResponseAt, priority: c.priority, intent: c.intent, last_message_at: c.lastMessageAt })));
    }
    case "list_tasks_due": {
      const rows = await ctx.db.select().from(schema.activities).where(and(eq(schema.activities.workspaceId, ws.id), isNull(schema.activities.completedAt), ctx.user ? eq(schema.activities.userId, ctx.user.id) : undefined, sql`${schema.activities.dueAt} <= ${new Date(Date.now() + 86400000)}`)).orderBy(schema.activities.dueAt).limit(15);
      return JSON.stringify(rows.map((a) => ({ id: a.id, type: a.type, title: a.title, due: a.dueAt, overdue: !!a.dueAt && a.dueAt < new Date() })));
    }
    case "send_message": {
      const { getContact } = await import("@/lib/services/contacts");
      const c = await getContact(ctx, input.contact_id);
      actions.push({ type: "confirm", token: await pending(ctx, "send_message", input), title: `Send ${input.channel} to ${fullName(c)}?`, detail: input.body.slice(0, 600) });
      return JSON.stringify({ status: "awaiting_user_confirmation", note: "A confirmation card is shown to the user. Tell them to tap Confirm to send." });
    }
    case "move_deal_stage": {
      const d = await ctx.db.query.deals.findFirst({ where: and(eq(schema.deals.id, input.deal_id), eq(schema.deals.workspaceId, ws.id)) });
      if (!d) return JSON.stringify({ error: "Deal not found" });
      const pl = await ctx.db.query.pipelines.findFirst({ where: eq(schema.pipelines.id, d.pipelineId) });
      const stage = pl?.stages.find((s) => s.name.toLowerCase() === input.stage_name.toLowerCase()) ?? pl?.stages.find((s) => s.name.toLowerCase().includes(input.stage_name.toLowerCase()));
      if (!stage) return JSON.stringify({ error: `No stage called "${input.stage_name}". Stages: ${pl?.stages.map((s) => s.name).join(", ")}` });
      if (stage.kind === "won" || stage.kind === "lost") return JSON.stringify({ error: "Won/Lost need a value or a reason — ask the user to do that in the pipeline." });
      actions.push({ type: "confirm", token: await pending(ctx, "move_deal_stage", { deal_id: d.id, stage_id: stage.id }), title: `Move “${d.title}” to ${stage.name}?`, detail: "This updates the pipeline and may send a conversion event to connected ad platforms." });
      return JSON.stringify({ status: "awaiting_user_confirmation" });
    }
    case "navigate": {
      const key = Object.keys(PAGES).find((k) => k === input.page.toLowerCase()) ?? Object.keys(PAGES).find((k) => input.page.toLowerCase().includes(k));
      if (!key) return JSON.stringify({ error: "Unknown page" });
      actions.push({ type: "navigate", href: PAGES[key]!, label: `Open ${key}` });
      return JSON.stringify({ ok: true, href: PAGES[key] });
    }
  }
  throw new Error(`Unhandled tool ${name}`);
}

export async function runAssistant(ctx: Ctx, history: { role: "user" | "assistant"; content: string }[], opts: { page?: string; voice?: boolean } = {}): Promise<AssistantReply> {
  const actions: ClientAction[] = [];
  const last = history[history.length - 1]?.content ?? "";
  if (!aiConfigured()) return guideReply(last);
  const ind = industryOf(ctx.workspace.settings);
  const plan = PLANS_CATALOG[normalizePlan(ctx.workspace.plan)];
  const system: Anthropic.TextBlockParam[] = [
    { type: "text", text: `You are the built-in AI assistant of ${process.env.NEXT_PUBLIC_PRODUCT_NAME ?? "Tempest Pulse"}, a marketing automation and CRM platform. You help users learn the product and you do work for them with tools.
Rules:
- Use tools to look things up or act instead of guessing. Never invent contacts, numbers or IDs; search first when the user names a person.
- create_lead and create_task act immediately. send_message and move_deal_stage only prepare an action the user confirms in a card — tell them to tap Confirm.
- If a tool returns an error or the user lacks permission, explain briefly and suggest what they can do.
- Reply in the user's language (Bangla or English). Be concise and friendly; use short bullet lists for steps.
- Never reveal API keys, passwords, codes or other secrets, and never ask for them.
${GUIDE}`, cache_control: { type: "ephemeral" } },
    { type: "text", text: `Context: user ${ctx.user?.name ?? "unknown"} (${ctx.roleName}) in workspace "${ctx.workspace.name}" — industry ${ind.label}, booked step "${ind.visit}", plan ${plan.name}, currency ${ctx.workspace.currency}, timezone ${ctx.workspace.timezone}, today ${new Date().toISOString().slice(0, 10)}. Current page: ${opts.page ?? "unknown"}.${opts.voice ? " The user is speaking by voice: answer in 1–3 short spoken sentences, no markdown, no lists, no URLs." : ""}` },
  ];
  const messages: Anthropic.MessageParam[] = history.slice(-12).map((m) => ({ role: m.role, content: m.content }));
  if (messages[0]?.role !== "user") messages.unshift({ role: "user", content: "(conversation started)" });
  const used: string[] = [];
  let reply = "";
  for (let turn = 0; turn < 6; turn++) {
    const { message } = await complete(ctx, { feature: opts.voice ? "assistant_voice" : "assistant", tier: "smart", effort: "low", system, messages, tools: TOOLS, maxTokens: 2000, cache: false });
    reply = message.content.filter((b): b is Anthropic.TextBlock => b.type === "text").map((b) => b.text).join("\n").trim() || reply;
    const calls = message.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");
    if (message.stop_reason !== "tool_use" || !calls.length) break;
    // append the full assistant content (thinking blocks included) and answer every tool call in one user message
    messages.push({ role: "assistant", content: message.content as Anthropic.ContentBlockParam[] });
    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const call of calls) {
      used.push(call.name);
      try {
        results.push({ type: "tool_result", tool_use_id: call.id, content: await runTool(ctx, call.name, call.input, actions) });
      } catch (e) {
        const msg = e instanceof z.ZodError ? `Invalid input: ${e.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}` : e instanceof ApiError ? e.message : "The action failed";
        results.push({ type: "tool_result", tool_use_id: call.id, content: msg, is_error: true });
      }
    }
    messages.push({ role: "user", content: results });
  }
  if (used.some((t) => ["create_lead", "create_task"].includes(t))) await audit(ctx, "assistant.action", "assistant", ctx.user?.id ?? "", undefined, { tools: used });
  return { reply: reply || "Done.", actions, tools: used, source: "ai" };
}

/** Execute a confirmed pending action (signed, 10-minute, same user and workspace). */
export async function confirmAction(ctx: Ctx, token: string) {
  const { payload } = await jwtVerify(token, secret()).catch(() => { throw new ApiError(400, "expired", "This confirmation expired — ask the assistant again"); });
  if (payload.uid !== ctx.user?.id || payload.ws !== ctx.workspace.id) throw new ApiError(403, "forbidden", "This action belongs to another user");
  const args = payload.args as Record<string, string>;
  if (payload.kind === "send_message") {
    const { sendMessage } = await import("@/lib/services/messaging");
    const r = await sendMessage(ctx, { contactId: args.contact_id!, channel: args.channel!, body: args.body, subject: args.subject, source: "human" });
    return { done: !!r.message && r.message.status !== "failed" && r.message.status !== "blocked", detail: r.blocked ?? r.message?.error ?? (r.deferredUntil ? `Scheduled for ${r.deferredUntil.toISOString()} (quiet hours)` : "Sent") };
  }
  if (payload.kind === "move_deal_stage") {
    const { changeStage } = await import("@/lib/services/leads");
    await changeStage(ctx, args.deal_id!, args.stage_id!);
    return { done: true, detail: "Deal moved" };
  }
  throw new ApiError(400, "invalid", "Unknown action");
}

/** Without an AI key: answer from the product guide and recognise "open …" requests, and say AI is not configured. */
function guideReply(text: string): AssistantReply {
  const t = text.toLowerCase();
  const actions: ClientAction[] = [];
  const page = Object.keys(PAGES).sort((a, b) => b.length - a.length).find((k) => t.includes(k));
  if (page && /(open|go to|show|take me|navigate|where)/.test(t)) actions.push({ type: "navigate", href: PAGES[page]!, label: `Open ${page}` });
  const lines = GUIDE.split("\n").slice(1).filter((l) => l.split(/[^a-z]+/i).some((w) => w.length > 3 && t.includes(w.toLowerCase())));
  const reply = lines.length
    ? `Here's how:\n${lines.slice(0, 3).join("\n")}\n\n(The full AI assistant switches on when an Anthropic API key is configured.)`
    : "I can explain any part of the platform — try “how do I import contacts?” or “open pipeline”. The full AI assistant (which can also create leads, tasks and answer data questions) switches on when an Anthropic API key is configured.";
  return { reply, actions, tools: [], source: "guide" };
}
