import type { TaskPanelArtifact, TaskPanelItem } from "@qjclaw/shared-types"

export interface TaskPanelSummary {
  creditsUsed: number
  messageCount: number
  artifactCount: number
  employeeCount: number
}

const douyinVisibleArtifactExtensions = new Set([".docx", ".mp4"])

function isDouyinTaskPanelExpert(expertName: string) {
  return /douyin|抖音/.test(expertName.toLowerCase())
}

function getTaskPanelArtifactExtension(artifact: TaskPanelArtifact) {
  const source = (artifact.path ?? artifact.url ?? artifact.name).trim()
  const cleanSource = source.split(/[?#]/, 1)[0] ?? ""
  const match = cleanSource.match(/\.([a-z0-9]+)$/i)
  return match ? `.${match[1].toLowerCase()}` : ""
}

export function getVisibleTaskPanelArtifacts(task: Pick<TaskPanelItem, "expertName" | "artifacts">) {
  if (!isDouyinTaskPanelExpert(task.expertName)) {
    return task.artifacts
  }

  return task.artifacts.filter((artifact) => douyinVisibleArtifactExtensions.has(getTaskPanelArtifactExtension(artifact)))
}

function toDateInputValue(date: Date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, "0")
  const day = String(date.getDate()).padStart(2, "0")
  return `${year}-${month}-${day}`
}

function addDays(date: Date, days: number) {
  const next = new Date(date)
  next.setDate(next.getDate() + days)
  return next
}

export function getDefaultTaskPanelDate() {
  return toDateInputValue(new Date())
}

export const mockTaskPanelItems: TaskPanelItem[] = [
  {
    id: "mock-task-content-plan",
    date: getDefaultTaskPanelDate(),
    expertName: "内容账号规划专家",
    taskTitle: "整理本周选题方向与发布节奏",
    status: "running",
    statusDetail: "正在汇总账号定位、目标人群和栏目节奏",
    creditsUsed: 1280,
    messageCount: 36,
    updatedAt: "10:42",
    artifacts: [
      { id: "artifact-content-outline", name: "选题规划草稿.md", kind: "文档", summary: "本周内容主线、栏目节奏与素材需求草案。", url: "/Users/edy/Documents/qianjiangclaw/tasks/content/选题规划草稿.md" },
      { id: "artifact-content-calendar", name: "发布日历.xlsx", kind: "表格", summary: "按平台拆分的发布排期与负责人视图。", url: "/Users/edy/Documents/qianjiangclaw/tasks/content/发布日历.xlsx" },
      { id: "artifact-content-persona", name: "目标人群画像.md", kind: "文档", summary: "核心受众痛点、决策因素与内容偏好。", url: "/Users/edy/Documents/qianjiangclaw/tasks/content/目标人群画像.md" },
      { id: "artifact-content-topics", name: "栏目选题池.csv", kind: "表格", summary: "可复用选题、关键词和参考链接集合。", url: "/Users/edy/Documents/qianjiangclaw/tasks/content/栏目选题池.csv" },
      { id: "artifact-content-brief", name: "账号定位简报.pdf", kind: "文档", summary: "账号定位、差异化表达和近期目标摘要。", url: "/Users/edy/Documents/qianjiangclaw/tasks/content/账号定位简报.pdf" }
    ]
  },
  {
    id: "mock-task-content-review",
    date: getDefaultTaskPanelDate(),
    expertName: "内容账号规划专家",
    taskTitle: "复盘昨日内容表现",
    status: "completed",
    statusDetail: "已完成互动数据摘要与优化建议",
    creditsUsed: 640,
    messageCount: 18,
    updatedAt: "09:18",
    artifacts: [
      { id: "artifact-content-review", name: "昨日内容复盘与下轮优化建议.md", kind: "文档", summary: "互动、转化和评论反馈的复盘结论。", url: "/Users/edy/Documents/qianjiangclaw/tasks/content/昨日内容复盘与下轮优化建议.md" }
    ]
  },
  {
    id: "mock-task-douyin-delivery",
    date: getDefaultTaskPanelDate(),
    expertName: "抖音专家",
    taskTitle: "生成短视频脚本与成片",
    status: "completed",
    statusDetail: "已完成脚本、成片和过程素材归档",
    creditsUsed: 1480,
    messageCount: 32,
    updatedAt: "11:48",
    artifacts: [
      { id: "artifact-douyin-script", name: "抖音口播脚本.docx", kind: "文档", summary: "数字人口播脚本、分镜节奏和字幕提示。", url: "/Users/edy/Documents/qianjiangclaw/tasks/douyin/抖音口播脚本.docx" },
      { id: "artifact-douyin-video", name: "抖音成片.mp4", kind: "视频", summary: "可发布的短视频成片。", url: "/Users/edy/Documents/qianjiangclaw/tasks/douyin/抖音成片.mp4" },
      { id: "artifact-douyin-notes", name: "执行过程记录.md", kind: "文档", summary: "运行日志和中间步骤记录。", url: "/Users/edy/Documents/qianjiangclaw/tasks/douyin/执行过程记录.md" },
      { id: "artifact-douyin-assets", name: "素材清单.xlsx", kind: "表格", summary: "镜头素材、来源和处理状态。", url: "/Users/edy/Documents/qianjiangclaw/tasks/douyin/素材清单.xlsx" },
      { id: "artifact-douyin-cover", name: "封面预览.png", kind: "图片", summary: "封面预览图。", url: "/Users/edy/Documents/qianjiangclaw/tasks/douyin/封面预览.png" }
    ]
  },
  {
    id: "mock-task-zhihu",
    date: getDefaultTaskPanelDate(),
    expertName: "知乎专家",
    taskTitle: "生成知乎回答结构",
    status: "completed",
    statusDetail: "已完成回答大纲与首版正文",
    creditsUsed: 920,
    messageCount: 24,
    updatedAt: "11:05",
    artifacts: [
      { id: "artifact-zhihu-answer", name: "知乎回答初稿.md", kind: "文档", summary: "问题拆解、回答结构和首版正文内容。", url: "/Users/edy/Documents/qianjiangclaw/tasks/zhihu/知乎回答初稿.md" }
    ]
  },
  {
    id: "mock-task-zhihu-research",
    date: getDefaultTaskPanelDate(),
    expertName: "知乎专家",
    taskTitle: "整理竞品问答素材",
    status: "running",
    statusDetail: "正在提取高赞回答结构和关键词",
    creditsUsed: 760,
    messageCount: 21,
    updatedAt: "11:36",
    artifacts: [
      { id: "artifact-zhihu-research", name: "竞品问答素材汇总-长文件名用于验证省略显示效果.xlsx", kind: "表格", summary: "高赞回答结构、关键词和引用素材汇总。", url: "/Users/edy/Documents/qianjiangclaw/tasks/zhihu/竞品问答素材汇总-长文件名用于验证省略显示效果.xlsx" }
    ]
  },
  {
    id: "mock-task-leads",
    date: getDefaultTaskPanelDate(),
    expertName: "平台精准线索专家",
    taskTitle: "筛选高意向线索名单",
    status: "pending",
    statusDetail: "等待线索表上传后开始处理",
    creditsUsed: 0,
    messageCount: 4,
    updatedAt: "12:10",
    artifacts: []
  },
  {
    id: "mock-task-poster",
    date: toDateInputValue(addDays(new Date(), -1)),
    expertName: "海报专家",
    taskTitle: "生成活动海报文案",
    status: "failed",
    statusDetail: "素材包缺少主视觉图片",
    creditsUsed: 360,
    messageCount: 12,
    updatedAt: "18:22",
    artifacts: [
      { id: "artifact-poster-brief", name: "活动海报文案草稿.txt", kind: "文档", summary: "活动主题、主标题和利益点文案草稿。", url: "/Users/edy/Documents/qianjiangclaw/tasks/poster/活动海报文案草稿.txt" }
    ]
  },
  {
    id: "mock-task-yesterday-leads",
    date: toDateInputValue(addDays(new Date(), -1)),
    expertName: "平台精准线索专家",
    taskTitle: "清洗昨日线索表",
    status: "completed",
    statusDetail: "已完成重复线索剔除和等级标注",
    creditsUsed: 520,
    messageCount: 16,
    updatedAt: "17:40",
    artifacts: [
      { id: "artifact-yesterday-leads", name: "昨日高意向线索清单.xlsx", kind: "表格", summary: "线索分级、跟进优先级和备注字段。", url: "/Users/edy/Documents/qianjiangclaw/tasks/leads/昨日高意向线索清单.xlsx" },
      { id: "artifact-yesterday-followup", name: "跟进话术建议.md", kind: "文档", summary: "按线索来源拆分的首轮沟通建议。", url: "/Users/edy/Documents/qianjiangclaw/tasks/leads/跟进话术建议.md" }
    ]
  }
]

export function summarizeTaskPanelItems(items: TaskPanelItem[]): TaskPanelSummary {
  const employeeCount = new Set(items.map((item) => item.expertName)).size
  const summary = items.reduce<TaskPanelSummary>((nextSummary, item) => {
    nextSummary.creditsUsed += item.creditsUsed ?? 0
    nextSummary.messageCount += item.messageCount ?? 0
    nextSummary.artifactCount += getVisibleTaskPanelArtifacts(item).length
    return nextSummary
  }, {
    creditsUsed: 0,
    messageCount: 0,
    artifactCount: 0,
    employeeCount
  })

  return summary
}

export async function loadTaskPanelItems(date: string): Promise<TaskPanelItem[]> {
  if (typeof window !== "undefined" && window.qjcDesktop) {
    return window.qjcDesktop.tasks.listByDate(date)
  }
  return mockTaskPanelItems.filter((item) => item.date === date)
}
