import test from 'node:test'
import assert from 'node:assert/strict'

import { buildSkillUploadPlan, shouldOfferSkillUpload } from './skillUploadPlan.js'

test('buildSkillUploadPlan only assembles runtime output and publication metadata', () => {
  const plan = buildSkillUploadPlan({
    name: 'AI 产品 PRD Skill',
    entries: [
      { path: 'SKILL.md', content: '# AI 产品 PRD Skill\n\n## 简介\n帮助产品经理撰写 PRD。' },
      { path: 'config/schema.json', content: '{"type":' },
    ],
    nodeId: '3',
    nodePath: '产品 / 需求',
    creatorName: '管理员',
  })

  assert.equal(plan.name, 'AI 产品 PRD Skill')
  assert.deepEqual(plan.entries.map(entry => entry.path), ['SKILL.md', 'config/schema.json'])
  assert.deepEqual(plan.missingFields, [])
  assert.equal(plan.canUpload, true)
  assert.deepEqual(Object.keys(plan).sort(), [
    'canUpload',
    'creatorName',
    'description',
    'entries',
    'missingFields',
    'name',
    'nodeId',
    'nodePath',
  ])
})

test('invalid or incomplete generated files never become a quality gate', () => {
  const plan = buildSkillUploadPlan({
    name: '自由生成 Skill',
    entries: [{ path: 'notes.txt', content: '运行时自由返回的内容' }, { path: 'bad.json', content: '{' }],
    nodeId: '6',
    nodePath: '流程 / 自由生成',
    creatorName: '管理员',
  })

  assert.equal(plan.canUpload, true)
  assert.deepEqual(plan.missingFields, [])
})

test('publication reports only real platform metadata still required', () => {
  const plan = buildSkillUploadPlan({
    name: '文本结果 Skill',
    description: '模型直接返回的创建结果。',
    creatorName: '',
  })

  assert.deepEqual(plan.missingFields, ['nodeId', 'creatorName'])
  assert.equal(plan.entries[0].path, 'SKILL.md')
})

test('SKILL.md title and intro can still provide publication metadata', () => {
  const plan = buildSkillUploadPlan({
    name: 'SKILL.md',
    entries: [{
      path: 'SKILL.md',
      content: '# 客户投诉分类 Skill\n\n## 简介\n**自动识别**投诉类别并提供处理建议。\n\n## 其他\n继续执行。',
    }],
    nodeId: '9',
    creatorName: '管理员',
  })

  assert.equal(plan.name, '客户投诉分类 Skill')
  assert.equal(plan.description, '自动识别投诉类别并提供处理建议。')
})

test('generated SKILL.md title wins over a later follow-up instruction', () => {
  const plan = buildSkillUploadPlan({
    messages: [{ role: 'user', content: '请沿用刚才会话，把三个文件再次写入并交付' }],
    entries: [{ path: 'SKILL.md', content: '# 流程文件审核 Skill\n\n## 概述\n审核企业 SOP。' }],
    nodeId: '15.3',
    creatorName: '管理员',
  })

  assert.equal(plan.name, '流程文件审核 Skill')
})

test('shouldOfferSkillUpload still recognizes runtime package text', () => {
  assert.equal(shouldOfferSkillUpload('SKILL.md：\n```markdown\n# 合同审查\n## 简介\n审查合同。\n```'), true)
  assert.equal(shouldOfferSkillUpload('普通对话回复'), false)
})
