function cleanTitle(text) {
  return String(text || '')
    .replace(/^#+\s*/, '')
    .replace(/^\*\*|\*\*$/g, '')
    .replace(/^["'“”‘’]+|["'“”‘’]+$/g, '')
    .replace(/^Skill\s*名称\s*[:：]\s*/i, '')
    .replace(/^名称\s*[:：]\s*/i, '')
    .trim()
}

function compactName(text) {
  const name = cleanTitle(text)
    .replace(/\s*(评测标准|评分标准|质量标准|示例|案例)\s*$/i, '')
    .replace(/\s+/g, ' ')
    .trim()
  return name.length > 40 ? `${name.slice(0, 40)}…` : name
}

function isGenericSkillTitle(text) {
  const normalized = compactName(text).toLowerCase()
  return !normalized || /^(skill|skill\.md|examples\.md|rubric\.md|简介|触发条件|输入参数|依赖工具|核心指令|输出规范|输出格式|输出模板|使用方式|边界条件|评分标准|示例|案例|适用场景|背景|目标|能力说明)$/i.test(normalized)
}

function stripFileExt(name) {
  return String(name || '').replace(/\.(md|markdown|txt|docx?|pdf|xlsx?|csv|zip)$/i, '')
}

function lastMessage(messages, role) {
  return [...(messages || [])].reverse().find(message => (
    message?.role === role && message?.content && !message?.isStreaming
  ))
}

function conversationMessages(messages, role) {
  return (messages || []).filter(message => (
    message?.role === role && message?.content && !message?.isStreaming
  ))
}

function extractExplicitSkillName(content) {
  const match = String(content || '').match(/(?:^|\n)\s*(?:#{1,4}\s*)?(?:Skill\s*)?名称\s*[:：]\s*([^\n]+)/i)
  return match?.[1] && !isGenericSkillTitle(match[1]) ? compactName(match[1]) : ''
}

function extractNameFromMarkdown(content) {
  const match = String(content || '').match(/(?:^|\n)\s*#\s+([^\n]+)/)
  return match?.[1] && !isGenericSkillTitle(match[1]) ? compactName(match[1]) : ''
}

function extractNameFromUserRequest(content) {
  const text = String(content || '').replace(/\s+/g, ' ')
  const quotedName = text.match(/(?:名为|叫做?|名称为)\s*["'“‘]([^"'”’]{2,50})["'”’]\s*的?\s*(?:Skill|skill|助手|工具|能力)/i)
  if (quotedName?.[1] && !isGenericSkillTitle(quotedName[1])) return compactName(quotedName[1])
  const match = text.match(/(?:我想要|我要|想要|想做|创建|生成|搭建|新建|做一个|做个|写一个|写个|搞一个|搞个|弄一个|弄个|开发|设计)\s*(?:一个|一份|个)?\s*([^，。！？\n]{2,50}?(?:Skill|skill|助手|工具|能力))/)
  return match?.[1] && !isGenericSkillTitle(match[1]) ? compactName(match[1]) : ''
}

function scoreSkillContent(content) {
  const text = String(content || '')
  let score = 0
  if (/(?:^|\n)\s*(?:#{1,4}\s*)?(?:Skill\s*)?名称\s*[:：]/i.test(text)) score += 20
  if (/^#\s+.+/m.test(text)) score += 12
  if (/##\s*简介/.test(text)) score += 8
  if (/##\s*触发条件/.test(text)) score += 8
  if (/##\s*核心指令/.test(text)) score += 8
  if (/SKILL\.md/i.test(text)) score += 5
  if (/examples\.md|示例/.test(text)) score -= 3
  return score
}

function extractMarkdownFence(content) {
  const fences = []
  const expression = /```(?:markdown|md)?[^\n]*\n([\s\S]*?)```/gi
  let match
  while ((match = expression.exec(String(content || ''))) !== null) {
    const body = String(match[1] || '').trim()
    if (body) fences.push(body)
  }
  fences.sort((left, right) => scoreSkillContent(right) - scoreSkillContent(left))
  return fences[0] || ''
}

function bestSkillContent(messages) {
  const candidates = []
  conversationMessages(messages, 'assistant').forEach((message, index) => {
    const content = String(message.content || '')
    const fenced = extractMarkdownFence(content)
    candidates.push({ content, score: scoreSkillContent(content) + index * 0.001 })
    if (fenced) candidates.push({ content: fenced, score: scoreSkillContent(fenced) + 10 + index * 0.001 })
  })
  conversationMessages(messages, 'user').forEach((message, index) => {
    const content = String(message.content || '')
    if (/^#\s+.+/m.test(content) || /##\s*简介/.test(content)) {
      candidates.push({ content, score: scoreSkillContent(content) + 9 + index * 0.001 })
    }
  })
  candidates.sort((left, right) => right.score - left.score)
  return candidates[0]?.content || ''
}

function buildTranscript(messages) {
  return (messages || [])
    .filter(message => (message?.role === 'user' || message?.role === 'assistant') && message?.content)
    .map(message => `${message.role === 'user' ? '用户' : '助手'}：${message.content}`)
    .join('\n\n')
}

export function inferSkillDraftFromMessages(messages, options = {}) {
  const user = lastMessage(messages, 'user')
  const sourceFile = options.sourceFile || null
  const sourceFileName = stripFileExt(sourceFile?.name || '')
  const bestContent = bestSkillContent(messages)
  const explicitName = [...conversationMessages(messages, 'assistant')]
    .reverse()
    .map(message => extractExplicitSkillName(message.content))
    .find(Boolean)
  const contentName = extractExplicitSkillName(bestContent) || extractNameFromMarkdown(bestContent)
  const userName = user?.content
    ? extractNameFromMarkdown(user.content) || extractNameFromUserRequest(user.content)
    : ''

  let name = explicitName || contentName
  if (!name && sourceFileName) name = `${sourceFileName}${/skill/i.test(sourceFileName) ? '' : ' Skill'}`
  if (!name && userName) name = userName
  if (!name && user?.content) name = compactName(user.content.split(/\r?\n/)[0])
  if (!name) name = 'AI 创建 Skill'

  const parts = []
  if (sourceFileName || options.sourceFilePath) {
    parts.push([
      `# ${name}`,
      '',
      '## 来源信息',
      sourceFileName ? `- 流程文件：${sourceFileName}` : '',
      options.sourceFilePath ? `- 所属架构：${options.sourceFilePath}` : '',
    ].filter(Boolean).join('\n'))
  }
  parts.push(bestContent || [
    `# ${name}`,
    '',
    '## 对话需求',
    buildTranscript(messages) || '暂无对话内容',
  ].join('\n'))

  return {
    name,
    description: parts.join('\n\n---\n\n').trim(),
  }
}
