import type { ExpertDefinition, ProjectRole } from "@qjclaw/shared-types"
import type { MessageListMessage } from "../chat/MessageList"
import type { ExpertGuideContent, ExpertKey, ExpertStarterPrompt } from "./ExpertsView"
import type { ExpertProject, ExpertVisualKey } from "../shell/ExpertTree"

export interface VideoStatusCardContent {
  title: string
  meta?: string
  hint?: string
}

const XIAOHONGSHU_STARTER_PROMPTS: ExpertStarterPrompt[] = [
  {
    title: "推荐平价火锅笔记",
    description: "适合门店探店、团购引流和高性价比种草。",
    prompt: "帮我做一篇推荐平价火锅的笔记，面向周末聚餐的年轻人，突出人均价格、招牌菜、环境氛围和适合拍照的点，给我标题、正文结构、封面文案和配图建议。"
  },
  {
    title: "抹茶奶酪欧包教程爆文",
    description: "把教程步骤改成更容易收藏转发的笔记。",
    prompt: "做一篇制作抹茶奶酪欧包教程的爆文，面向烘焙新手，突出材料清单、关键步骤、失败避坑和成品口感，给我小红书标题、正文、标签和封面文案。"
  },
  {
    title: "通勤女生春季穿搭笔记",
    description: "围绕职场通勤、显瘦配色和一周搭配展开。",
    prompt: "给通勤女生做一篇春季穿搭笔记，面向 25-35 岁职场女性，突出显瘦、舒适、适合办公室和约会切换，给我 5 个标题、正文结构、单品搭配和拍摄建议。"
  },
  {
    title: "年轻女性防晒霜爆款图文",
    description: "适合护肤品卖点拆解、场景种草和转化。",
    prompt: "帮我策划一篇年轻女性防晒霜爆款图文笔记，面向 20-30 岁通勤和户外场景用户，突出肤感、防晒力、妆前适配和补涂体验，给我标题、正文、封面文案、配图脚本和标签。"
  }
]

export function getProjectDisplayName(project: ExpertProject | undefined, defaultChatName = "千匠问天"): string {
  return project?.displayName ?? project?.name ?? defaultChatName
}

export function resolveExpertKey(project: ExpertProject | undefined): ExpertKey {
  const seed = [project?.platform, project?.displayName, project?.name, project?.id]
    .filter(Boolean)
    .join(" ")
    .toLowerCase()

  if (/xiaohongshu|xhs|rednote|小红书/.test(seed)) {
    return "xiaohongshu"
  }
  if (/douyin|抖音/.test(seed)) {
    return "douyin"
  }
  if (/tiktok/.test(seed)) {
    return "douyin"
  }
  if (/wechat|weixin|公众号|微信/.test(seed)) {
    return "wechat"
  }
  if (/zhihu|知乎/.test(seed)) {
    return "zhihu"
  }
  if (/content-account|planner|账号规划|内容账号规划|内容创作/.test(seed)) {
    return "planner"
  }
  if (/\bgeo\b/.test(seed)) {
    return "geo"
  }
  if (/browser|automation|chrome|playwright|web|浏览器|自动化/.test(seed)) {
    return "browser"
  }
  return "general"
}

export function resolveExpertVisualKey(project?: ExpertProject, definition?: ExpertDefinition): ExpertVisualKey {
  const seed = [definition?.id, definition?.name, project?.platform, project?.displayName, project?.name, project?.id]
    .filter(Boolean)
    .join(" ")
    .toLowerCase()

  if (/xiaohongshu|xhs|rednote|小红书/.test(seed)) {
    return "xiaohongshu"
  }
  if (/douyin|抖音/.test(seed)) {
    return "douyin"
  }
  if (/tiktok/.test(seed)) {
    return "tiktok"
  }
  if (/wechat|weixin|公众号|微信/.test(seed)) {
    return "wechat"
  }
  if (/zhihu|知乎/.test(seed)) {
    return "zhihu"
  }
  if (/content-account|planner|账号规划|内容账号规划|内容创作/.test(seed)) {
    return "planner"
  }
  if (/precision-leads|线索|lead/.test(seed)) {
    return "leads"
  }
  if (/sales-champion|销售冠军|销冠|sales champion/.test(seed)) {
    return "sales"
  }
  if (/poster|海报/.test(seed)) {
    return "poster"
  }
  if (/(^|[\s-])x($|[\s-])|twitter/.test(seed)) {
    return "x"
  }
  if (/\bgeo\b/.test(seed)) {
    return "geo"
  }
  if (/browser|automation|chrome|playwright|web|浏览器|自动化/.test(seed)) {
    return "browser"
  }
  return "general"
}

export function buildDouyinVideoStatusCard(message: MessageListMessage, expertKey: ExpertKey): VideoStatusCardContent | null {
  if (expertKey !== "douyin" || message.role !== "assistant" || message.streamState !== "streaming" || message.content.trim()) {
    return null
  }

  const title = message.statusLabel?.trim() ?? ""
  const detail = message.statusDetail?.trim() ?? ""
  const seed = `${title} ${detail}`.toLowerCase()
  const looksLikeVideoGeneration = /视频|口播|omnihuman|seedance|远端|生成|分钟|引擎|预计/.test(seed)
  if (!looksLikeVideoGeneration) {
    return null
  }

  const [meta, eta, hint] = detail.split(" | ").map((item) => item.trim()).filter(Boolean)
  const metaParts = [meta, eta].filter(Boolean)
  return {
    title: title || "视频正在生成中...",
    meta: metaParts.length ? metaParts.join(" · ") : undefined,
    hint: hint || "已进入长任务生成阶段，客户端会持续刷新状态。"
  }
}

function getExpertGuide(project: ExpertProject | undefined): ExpertGuideContent {
  switch (resolveExpertKey(project)) {
    case "xiaohongshu":
      return {
        greeting: "准备好了，开始种草",
        summary: "",
        starterPrompts: XIAOHONGSHU_STARTER_PROMPTS,
        prompts: XIAOHONGSHU_STARTER_PROMPTS.map((item) => item.prompt)
      }
    case "douyin":
      return {
        greeting: "你可以直接说目标，我会按抖音内容和发布节奏来拆解。",
        summary: "适合抖音脚本策划、短视频结构、口播优化和发布执行建议。",
        prompts: [
          "帮我规划 5 条抖音短视频选题，目标是引流到私域。",
          "把这个产品介绍改成 30 秒抖音口播脚本。",
          "给我一个抖音视频的镜头脚本和字幕节奏。",
          "分析这个选题为什么更适合抖音而不是小红书。"
        ]
      }
    case "planner":
      return {
        greeting: "今天想创作什么内容？",
        summary: "说清目标、平台和受众，我帮你拆成可执行的创作方案。",
        intro: "最好一次说明主题、面向谁、想达到什么目标、偏好什么形式和风格。",
        requirementChecklist: ["主题", "平台", "受众", "目标", "形式", "风格"],
        prompts: [
          "帮我策划一周的多平台内容日历",
          "把一个产品卖点改成不同平台的种草内容",
          "针对25-35岁职场女性策划一个内容IP定位"
        ]
      }
    case "wechat":
      return {
        greeting: "来，一起打磨一篇好文章",
        summary: "从选题到涨粉，我帮你把公众号内容体系跑通。",
        intro: "公众号文章需要兼顾打开率、完读率和转化。你可以直接说选题方向，我会帮你补全框架、标题和结构。",
        requirementChecklist: ["选题方向", "文章类型", "目标读者", "核心信息", "期望效果"],
        workflowSteps: ["选题规划与内容日历", "标题优化（提高打开率）", "文章结构梳理与排版建议", "涨粉策略与粉丝运营"],
        prompts: [
          "帮我策划一篇公众号科普长文，主题是职场效率工具，目标读者是职场新人。",
          "分析生活类公众号的选题方向，给出优化建议",
          "给我5个能涨粉的互动活动方案"
        ]
      }
    case "geo":
      return {
        greeting: "让 AI 搜索引擎主动引用你的品牌",
        summary: "",
        intro: "告诉我你的品牌/产品、核心关键词和目标平台（百度AI搜索/DeepSeek/豆包），我会先让诊断师评估你的AI可见性现状。",
        requirementChecklist: ["品牌/产品", "目标平台", "核心关键词", "竞品参考"],
        roles: [
          { id: "diagnostician", name: "诊断师", icon: "search", skillIds: ["geo-diagnostician"], description: "品牌AI可见性评估与信息一致性审计" },
          { id: "strategist", name: "策略师", icon: "lightbulb", skillIds: ["geo-strategist"], description: "关键词策略与渠道矩阵" },
          { id: "content-creator", name: "内容师", icon: "pen", skillIds: ["geo-content-creator"], description: "AI优化内容创作与效力自检" },
          { id: "tech-advisor", name: "技术顾问", icon: "settings", skillIds: ["geo-tech-advisor"], description: "Schema部署与监测体系" },
        ] satisfies ProjectRole[],
        prompts: [
          "帮我诊断瑞幸咖啡在百度AI中的AI可见性，竞品星巴克",
          "为茶百道制定GEO优化策略，目标平台豆包",
          "对比一下霸王茶姬、茶颜悦色和奈雪的茶，在豆包中被推荐的差异"
        ]
      }
    case "zhihu":
      return {
        greeting: "在知乎，专业是最好的流量",
        summary: "",
        intro: "知乎用户看重专业深度和真实经验。告诉我你的专业领域和人设目标，我来帮你策划内容策略。",
        requirementChecklist: ["专业领域", "人设定位", "目标受众", "内容类型", "更新频率"],
        workflowSteps: ["人设定位：你希望被记住的专业标签是什么？", "选题策略：追踪热点问题 vs 深耕垂直领域", "回答结构：开篇抓人 → 专业拆解 → 金句收尾"],
        prompts: [
          "帮我找5个职场领域的高关注问题，写深度回答",
          "给我设计一个知乎个人主页的专业定位方案",
          "把这篇公众号文章改写成知乎回答风格"
        ]
      }
    case "browser":
      return {
        greeting: "适合处理浏览器自动化、采集、表单填写和发布流程设计。",
        summary: "围绕浏览器操作自动化、信息采集、流程编排和执行前检查提供帮助。",
        prompts: [
          "帮我设计一个浏览器自动采集选题的执行流程。",
          "梳理抖音发布前需要自动检查的页面步骤。",
          "如果要自动登录并抓取页面数据，我应该先确认哪些风险点？",
          "把小红书和抖音的发布流程拆成可自动化的步骤。"
        ]
      }
    default:
      return {
        greeting: "说清你的目标，我会先帮你拆成可执行步骤",
        summary: "适合梳理需求、生成方案、组织信息和推进执行",
        prompts: [
          "你好啊",
          "请做一个自我介绍，给出一个你的能力清单"
        ]
      }
  }
}

export function getExpertGuideContent(project: ExpertProject | undefined): ExpertGuideContent {
  const expertKey = resolveExpertKey(project)
  if (expertKey !== "douyin") {
    return getExpertGuide(project)
  }

  return {
    greeting: "先把这条抖音视频的条件说清楚，我会先帮你整理需求并给出预览。",
    summary: "适合抖音视频需求补全、文案与分镜预览、数字人口播和纯画面路线判断。",
    intro: "最好一次说明主题、给谁看、想达到什么目标、风格、时长、做数字人还是纯画面，以及现在有没有图片或音频。",
    requirementChecklist: [
      "主题",
      "人群",
      "目标",
      "风格",
      "时长",
      "视频类型",
      "素材"
    ],
    routeOptions: [
      {
        title: "数字人口播",
        detail: "适合数字人口播、知识讲解、产品说明。继续生成前通常要确认人物图片，以及现成音频或男声/女声配音。",
        accent: "host"
      },
      {
        title: "纯画面展示",
        detail: "适合氛围片、空镜、场景展示、画面加旁白。先把视频秒数说清楚，再出文案和分镜预览。",
        accent: "visual"
      }
    ],
    workflowSteps: [
      "补全 brief",
      "生成预览",
      "确认后开跑视频"
    ],
    // continueHint: "看完预览后，你可以直接回复：继续生成；如果要改，直接回复：修改第几镜 + 你的修改意见。",
    placeholder: "例如：做一个讲天气预报的抖音视频，给职场人看，目标是科普，男声数字人口播，10 秒，氛围感，我会上传人物照片，先给我文案和分镜预览。",
    prompts: [
      "做一个海边视频不要出现人物，给附近上班族看，目标是到店引流，纯画面展示，15 秒，真实手机拍摄感",
      "做一个护肤品种草短视频，给 25-35 岁女性看，目标是种草转化，纯画面加旁白，10 秒，精致广告感"
    ]
  }
}
