import { createPinterestBoard, createPinterestPin, hasPinterestToken } from "@/lib/pinterest-api";
import { preflightPinDraft, summarizePreflight } from "@/lib/pin-preflight";
import { checkCommercialGateWithHeartbeat, taskAction } from "@/lib/commercial";
import { addAudit, createId, Database, readDb, writeDb } from "@/lib/store";
import { PinterestAutomationTask, PinterestBoard, PinterestTrendResearch } from "@/lib/types";

export async function runDueTasks(limit = 5) {
  const db = await readDb();
  const due = db.tasks
    .filter((task) => task.status === "pending")
    .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
    .slice(0, Math.max(1, Math.min(limit, 20)));

  const results = [];
  for (const task of due) {
    results.push(await runTask(task.id));
  }
  return results;
}

export async function runTask(taskId: string) {
  const db = await readDb();
  const task = db.tasks.find((item) => item.id === taskId);
  if (!task) return { ok: false, taskId, error: "task not found" };
  if (task.status !== "pending") return { ok: false, taskId, error: `task is ${task.status}` };

  task.status = "running";
  task.updatedAt = new Date().toISOString();
  await writeDb(db);

  try {
    const current = await readDb();
    const currentTask = current.tasks.find((item) => item.id === taskId);
    if (!currentTask) throw new Error("task disappeared while running");
    const action = taskAction(currentTask.type);
    if (action) {
      const gate = await checkCommercialGateWithHeartbeat(current, action);
      if (!gate.ok) {
        currentTask.status = "failed";
        currentTask.result = gate.error;
        currentTask.updatedAt = new Date().toISOString();
        addAudit(current, {
          type: "task",
          actor: "system",
          title: `商业授权拦截：${currentTask.type}`,
          detail: gate.error,
          status: "failed",
        });
        await writeDb(current);
        return { ok: false, taskId, error: gate.error };
      }
    }
    const result = await executeTask(current, currentTask);
    currentTask.status = result.ok ? "completed" : "failed";
    currentTask.result = result.ok ? result.message : result.error;
    currentTask.updatedAt = new Date().toISOString();
    addAudit(current, {
      type: "task",
      actor: auditActorForExecutor(currentTask.executorMode),
      title: result.ok ? `任务完成：${currentTask.type}` : `任务失败：${currentTask.type}`,
      detail: currentTask.result || "",
      status: result.ok ? "completed" : "failed",
    });
    await writeDb(current);
    return { ok: result.ok, taskId, result: currentTask.result };
  } catch (error) {
    const failed = await readDb();
    const failedTask = failed.tasks.find((item) => item.id === taskId);
    const message = error instanceof Error ? error.message : String(error);
    if (failedTask) {
      failedTask.status = "failed";
      failedTask.result = message;
      failedTask.updatedAt = new Date().toISOString();
      addAudit(failed, {
        type: "task",
        actor: "system",
        title: `任务异常：${failedTask.type}`,
        detail: message,
        status: "failed",
      });
      await writeDb(failed);
    }
    return { ok: false, taskId, error: message };
  }
}

function auditActorForExecutor(mode: PinterestAutomationTask["executorMode"]) {
  if (mode === "api") return "api" as const;
  if (mode === "browser") return "browser" as const;
  return "system" as const;
}

async function executeTask(db: Database, task: PinterestAutomationTask) {
  if (task.type === "check_health") return checkHealth(db);
  if (task.type === "research_trends") return researchTrends(db, task);
  if (task.type === "create_pin_draft") return createDraftFromTask(db, task);
  if (task.type === "publish_pin") return publishPendingPin(db, task);
  if (task.type === "create_board") return createBoardFromTask(db, task);
  if (task.type === "read_pin_analytics") return readAnalyticsPlaceholder(db, task);
  if (task.type === "catalog_check") return { ok: true as const, message: "Catalog 检查任务已占位：下一阶段接入 Catalog API / feed report。" };
  if (task.type === "ads_report") return { ok: true as const, message: "Ads 报表任务已占位：下一阶段接入 Ads reporting API。" };
  if (task.type === "browser_snapshot") return { ok: true as const, message: "Browser snapshot 任务已占位：下一阶段接入 CDP 页面诊断。" };
  return { ok: false as const, error: `unsupported task type: ${task.type}` };
}

function checkHealth(db: Database) {
  const required = ["boards:read", "boards:write", "pins:read", "pins:write"];
  const missing = required.filter((scope) => !db.account.scopes.includes(scope));
  const notes = [
    hasPinterestToken() ? "env token configured" : "PINTEREST_ACCESS_TOKEN missing",
    db.account.businessAccount ? "business account marked" : "business account not marked",
    missing.length ? `missing scopes: ${missing.join(", ")}` : "basic content scopes marked",
  ];
  return { ok: true as const, message: notes.join("; ") };
}

function researchTrends(db: Database, task: PinterestAutomationTask) {
  const keyword = String(task.payload.keyword || task.payload.brief || "product").slice(0, 80);
  const now = new Date().toISOString();
  const base = keyword.replace(/^围绕关键词「|」.*$/g, "").trim() || keyword;
  const research: PinterestTrendResearch = {
    id: createId("trend"),
    seedKeyword: base,
    market: String(task.payload.market || "US"),
    terms: [
      { keyword: `${base} ideas`, intent: "idea", score: 78, reason: "Pinterest 用户常以灵感和方案词搜索。" },
      { keyword: `${base} aesthetic`, intent: "seasonal", score: 70, reason: "适合做视觉风格和图板主题扩展。" },
      { keyword: `${base} shopping`, intent: "shopping", score: 66, reason: "适合承接 Product Pin、Catalog 和站外落地页。" },
    ],
    summary: "已生成本地趋势研究占位数据。接入 Pinterest Trends API 后替换为真实趋势。",
    createdAt: now,
  };
  db.trendResearch.unshift(research);
  return { ok: true as const, message: `已生成趋势研究：${research.seedKeyword}` };
}

function createDraftFromTask(db: Database, task: PinterestAutomationTask) {
  const board = db.boards[0];
  if (!board) return { ok: false as const, error: "没有可用图板，请先创建 board" };
  const now = new Date().toISOString();
  const title = String(task.payload.title || "Pinterest growth idea").slice(0, 100);
  db.pinDrafts.unshift({
    id: createId("pin"),
    boardId: board.id,
    title,
    description: String(task.payload.description || task.payload.brief || "AI 生成的 Pin 草稿，等待人工确认。").slice(0, 500),
    link: typeof task.payload.productUrl === "string" ? task.payload.productUrl : undefined,
    mediaType: "image",
    keywords: typeof task.payload.keyword === "string" ? [task.payload.keyword] : [],
    status: "pending_review",
    createdAt: now,
    updatedAt: now,
  });
  return { ok: true as const, message: `已创建 Pin 草稿：${title}` };
}

async function publishPendingPin(db: Database, _task: PinterestAutomationTask) {
  const requestedId = typeof _task.payload.pinDraftId === "string" ? _task.payload.pinDraftId : "";
  const pin = requestedId
    ? db.pinDrafts.find((item) => item.id === requestedId)
    : db.pinDrafts.find((item) => item.status === "scheduled" || item.status === "pending_review");
  if (!pin) return { ok: false as const, error: "没有可发布的 Pin 草稿" };
  if (pin.status === "pending_review" && db.riskLimits.requireApprovalForPublish) {
    return { ok: false as const, error: `Pin ${pin.id} 仍在 pending_review，需先人工批准。` };
  }
  const board = db.boards.find((item) => item.id === pin.boardId);
  const preflight = preflightPinDraft(db, pin);
  if (!preflight.ok) return { ok: false as const, error: summarizePreflight(preflight) };
  if (!board?.apiBoardId) return { ok: false as const, error: "目标图板缺少 apiBoardId，请先通过 Pinterest API 创建或同步图板。" };
  const result = await createPinterestPin({ ...pin, apiBoardId: board.apiBoardId });
  if (!result.ok) return { ok: false as const, error: result.error };
  pin.apiPinId = result.data.id;
  pin.status = "published";
  pin.evidence = `Pinterest API pin id: ${result.data.id}`;
  pin.updatedAt = new Date().toISOString();
  return { ok: true as const, message: `已通过 Pinterest API 发布 Pin：${result.data.id}` };
}

async function createBoardFromTask(db: Database, task: PinterestAutomationTask) {
  const name = String(task.payload.name || "Pinterest Ideas").slice(0, 100);
  const privacy: "PUBLIC" | "PROTECTED" | "SECRET" =
    task.payload.privacy === "SECRET" || task.payload.privacy === "PROTECTED" ? task.payload.privacy : "PUBLIC";
  const now = new Date().toISOString();
  const board: PinterestBoard = {
    id: createId("board"),
    name,
    description: String(task.payload.description || ""),
    privacy,
    createdAt: now,
    updatedAt: now,
  };
  if (task.payload.execute === true) {
    const result = await createPinterestBoard(board);
    if (!result.ok) return { ok: false as const, error: result.error };
    board.apiBoardId = result.data.id;
  }
  db.boards.unshift(board);
  return { ok: true as const, message: task.payload.execute === true ? `已创建 API 图板：${name}` : `已创建本地图板：${name}` };
}

function readAnalyticsPlaceholder(_db: Database, _task: PinterestAutomationTask) {
  return {
    ok: true as const,
    message: "Pin Analytics 任务已占位：下一阶段接入 /pins/{pin_id}/analytics，读取 impressions、saves、pin clicks、outbound clicks。",
  };
}
