import { OperatorPlan, OperatorPlanItem, OperatorPlanItemType } from "@/lib/types";
import { createId } from "@/lib/store";

export function createOperatorPlan(input: {
  command: string;
  goal?: string;
  date?: string;
  keyword?: string;
  productUrl?: string;
  contentBrief?: string;
}) {
  const now = new Date();
  const planId = createId("op");
  const items: OperatorPlanItem[] = [];
  const date = input.date || now.toISOString().slice(0, 10);

  const add = (type: OperatorPlanItemType, brief: string, hourOffset = items.length) => {
    const scheduledAt = new Date(now.getTime() + hourOffset * 60 * 60 * 1000).toISOString();
    items.push({
      id: createId("opitem"),
      planId,
      type,
      brief,
      status: "pending",
      scheduledAt,
    });
  };

  add("check_health", "检查 Pinterest OAuth、企业账号、API scope、Business/Analytics/Catalog 就绪状态。");

  if (input.keyword) {
    add("research_trends", `围绕关键词「${input.keyword}」做趋势、搜索意图和图板主题研究。`);
  }

  if (input.contentBrief || input.productUrl || input.keyword) {
    add(
      "create_pin_drafts",
      `生成 Pin 草稿：${input.contentBrief || input.keyword || "基于产品资料生成内容"}${input.productUrl ? `，目标链接 ${input.productUrl}` : ""}。`,
    );
    add("publish_pin", "把通过审核的 Pin 草稿排队发布，默认不自动发布，等待人工确认。");
  }

  add("read_analytics", "读取自有 Pin 和图板表现，分析保存、点击、站外点击和互动趋势。");
  add("crm_follow_up", "把 Pin/广告/网站产生的高价值信号整理进 CRM，并给出后续动作。");
  add("report", "汇总今日 Pinterest 内容、趋势、商机、广告和下一步建议。");

  const plan: OperatorPlan = {
    id: planId,
    date,
    goal: input.goal || inferGoal(input),
    status: "draft",
    summary: "已创建 Pinterest 运营计划，等待执行。",
    createdFromCommand: input.command,
    items,
    createdAt: now.toISOString(),
    updatedAt: now.toISOString(),
  };
  return plan;
}

function inferGoal(input: { keyword?: string; productUrl?: string; contentBrief?: string }) {
  const parts = [];
  if (input.keyword) parts.push(`研究「${input.keyword}」趋势`);
  if (input.contentBrief || input.productUrl) parts.push("生成并发布 Pin 内容");
  parts.push("分析表现并沉淀商机");
  return parts.join("，");
}
