import assert from 'node:assert/strict'
import test from 'node:test'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import JSZip from 'jszip'

import { materializePackageBufferToSession } from './skill-run.js'

test('materializePackageBufferToSession writes raw markdown uploads as SKILL.md', async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-package-session-'))
  try {
    await materializePackageBufferToSession({
      buffer: Buffer.from('# 风险评估\n\n## 简介\n识别风险。'),
      packageKey: 'pkg/2026-06-27/file_123_SKILL.md',
      sessionDir: dir,
    })

    const content = fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8')
    assert.match(content, /# 风险评估/)
  } finally {
    fs.rmSync(dir, { recursive: true, force: true })
  }
})

test('materializePackageBufferToSession keeps zip entries inside the session directory', async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-package-session-'))
  const outside = path.join(path.dirname(dir), 'escape.md')
  const zip = new JSZip()
  zip.file('SKILL.md', '# 合规审查\n\n## 简介\n检查合规风险。')
  zip.file('../escape.md', 'should not be written')
  zip.file('__MACOSX/._SKILL.md', 'metadata')

  try {
    const written = await materializePackageBufferToSession({
      buffer: await zip.generateAsync({ type: 'nodebuffer' }),
      packageKey: 'pkg/2026-06-27/skill.zip',
      sessionDir: dir,
    })

    assert.deepEqual(written, ['SKILL.md'])
    assert.equal(fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8').startsWith('# 合规审查'), true)
    assert.equal(fs.existsSync(outside), false)
    assert.equal(fs.existsSync(path.join(dir, '__MACOSX')), false)
  } finally {
    fs.rmSync(dir, { recursive: true, force: true })
    fs.rmSync(outside, { force: true })
  }
})
