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

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

const expertArtifactExtensionRules: { pattern: RegExp; extensions: Set<string> }[] = [
  { pattern: /小红书|xiaohongshu|xhs|rednote/i,       extensions: new Set([".md", ".docx", ".xlsx", ".png", ".jpg"]) },
  { pattern: /抖音|douyin/i,                           extensions: new Set([".docx", ".mp4"]) },
  { pattern: /微信|公众号|wechat|weixin/i,              extensions: new Set([".md", ".docx", ".xlsx"]) },
  { pattern: /知乎|zhihu/i,                            extensions: new Set([".md", ".docx", ".xlsx"]) },
  { pattern: /内容创作|内容规划|内容账号|content-account|planner/i, extensions: new Set([".md", ".docx", ".xlsx", ".csv", ".pdf"]) },
  { pattern: /AI推荐|推荐引擎|geo/i,                    extensions: new Set([".md", ".xlsx", ".csv"]) }
]

const standaloneExpertPatterns: RegExp[] = expertArtifactExtensionRules.map((rule) => rule.pattern)

function isStandaloneExpert(expertName: string): boolean {
  return standaloneExpertPatterns.some((pattern) => pattern.test(expertName))
}

function resolveExpertArtifactExtensions(expertName: string): Set<string> | null {
  for (const rule of expertArtifactExtensionRules) {
    if (rule.pattern.test(expertName)) {
      return rule.extensions
    }
  }
  return null
}

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">) {
  const allowedExtensions = resolveExpertArtifactExtensions(task.expertName)
  if (!allowedExtensions) {
    return task.artifacts
  }

  return task.artifacts.filter((artifact) => allowedExtensions.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-wechat-article",
    date: getDefaultTaskPanelDate(),
    expertName: "微信公众号运营",
    taskTitle: "撰写公众号推文与涨粉计划",
    status: "completed",
    statusDetail: "已完成推文草稿、排版建议和涨粉策略",
    creditsUsed: 1050,
    messageCount: 28,
    updatedAt: "14:15",
    artifacts: [
      { id: "artifact-wechat-draft", name: "公众号推文草稿.md", kind: "文档", summary: "推文正文、标题方案和封面图建议。", url: "/Users/edy/Documents/qianjiangclaw/tasks/wechat/公众号推文草稿.md" },
      { id: "artifact-wechat-plan", name: "涨粉运营计划.docx", kind: "文档", summary: "月度涨粉目标、活动策划和转化路径。", url: "/Users/edy/Documents/qianjiangclaw/tasks/wechat/涨粉运营计划.docx" },
      { id: "artifact-wechat-calendar", name: "推文排期表.xlsx", kind: "表格", summary: "按日期拆分的选题、撰稿人和发布状态。", url: "/Users/edy/Documents/qianjiangclaw/tasks/wechat/推文排期表.xlsx" }
    ]
  },
  {
    id: "mock-task-geo-optimize",
    date: getDefaultTaskPanelDate(),
    expertName: "AI推荐引擎优化",
    taskTitle: "优化品牌在AI搜索引擎中的可见性",
    status: "completed",
    statusDetail: "已完成关键词分析、内容优化建议和技术审计",
    creditsUsed: 880,
    messageCount: 22,
    updatedAt: "15:30",
    artifacts: [
      { id: "artifact-geo-report", name: "AI搜索可见性优化报告.md", kind: "文档", summary: "品牌在主流AI搜索引擎中的现状分析与优化建议。", url: "/Users/edy/Documents/qianjiangclaw/tasks/geo/AI搜索可见性优化报告.md" },
      { id: "artifact-geo-keywords", name: "GEO关键词矩阵.xlsx", kind: "表格", summary: "按搜索意图分类的关键词覆盖率和竞争度。", url: "/Users/edy/Documents/qianjiangclaw/tasks/geo/GEO关键词矩阵.xlsx" }
    ]
  }
]

export function summarizeTaskPanelItems(items: TaskPanelItem[]): TaskPanelSummary {
  const standaloneItems = items.filter((item) => isStandaloneExpert(item.expertName))
  const employeeCount = new Set(standaloneItems.map((item) => item.expertName)).size
  const summary = standaloneItems.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[]> {
  let items: TaskPanelItem[]
  if (typeof window !== "undefined" && window.qjcDesktop) {
    items = await window.qjcDesktop.tasks.listByDate(date)
  } else {
    items = mockTaskPanelItems.filter((item) => item.date === date)
  }
  return items.filter((item) => isStandaloneExpert(item.expertName))
}
