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

import {
  fetchGeneratedPackageEntries,
  isReadableGeneratedPackageFile,
} from './generatedPackageFiles.js'

test('isReadableGeneratedPackageFile keeps text package files and skips binary assets', () => {
  assert.equal(isReadableGeneratedPackageFile('SKILL.md'), true)
  assert.equal(isReadableGeneratedPackageFile('examples.md'), true)
  assert.equal(isReadableGeneratedPackageFile('rubric.md'), true)
  assert.equal(isReadableGeneratedPackageFile('config/schema.json'), true)
  assert.equal(isReadableGeneratedPackageFile('images/logo.png'), false)
  assert.equal(isReadableGeneratedPackageFile('../secret.md'), false)
})

test('fetchGeneratedPackageEntries loads generated text files as package entries', async () => {
  const requested = []
  const fetcher = async (url) => {
    requested.push(url)
    if (url.includes('SKILL.md')) {
      return { ok: true, text: async () => '# 客户投诉分级与响应助手\n\n## 简介\n处理投诉。\n' }
    }
    if (url.includes('examples.md')) {
      return { ok: true, text: async () => '# 示例\n' }
    }
    return { ok: false, text: async () => '' }
  }

  const entries = await fetchGeneratedPackageEntries({
    sessionId: 'abc_123',
    files: ['SKILL.md', 'examples.md', 'logo.png', '../secret.md'],
    apiBase: 'http://localhost:4000/api',
    fetcher,
  })

  assert.deepEqual(entries.map(entry => entry.path), ['SKILL.md', 'examples.md'])
  assert.match(entries[0].content, /客户投诉分级与响应助手/)
  assert.equal(requested.length, 2)
  assert.match(requested[0], /outputs\/abc_123\/SKILL\.md$/)
})
