#!/usr/bin/env node
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import {
  buildBundledSkillManifest,
  isBundledSkillPathExcluded,
  normalizeBundledSkillPath,
} from './bundled-skills-utils.mjs'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
const sourceDir = path.resolve(process.env.CODEX_SKILLS_DIR || path.join(os.homedir(), '.codex', 'skills'))
const targetDir = path.join(rootDir, 'bundled-skills')
const tempDir = path.join(rootDir, `.bundled-skills.tmp-${process.pid}`)

if (!fs.existsSync(sourceDir) || !fs.statSync(sourceDir).isDirectory()) {
  throw new Error(`没有找到本机 Skill 目录：${sourceDir}`)
}

fs.rmSync(tempDir, { recursive: true, force: true })
fs.cpSync(sourceDir, tempDir, {
  recursive: true,
  filter(source) {
    const rel = normalizeBundledSkillPath(path.relative(sourceDir, source))
    return !rel || !isBundledSkillPathExcluded(rel)
  },
})

const manifest = buildBundledSkillManifest(tempDir)
fs.writeFileSync(path.join(tempDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`)
fs.writeFileSync(path.join(tempDir, 'README.md'), [
  '# AIPROS 内置 Skill 库',
  '',
  `本包包含 ${manifest.skillCount} 个可发布 Skill（用户级与 Codex 系统级合计）。`,
  '',
  '- 首次运行 `npm start` 或 `npm run local` 时会自动导入并发布到 AIPROS。',
  '- 每个 Skill 的完整目录会原样打成独立 ZIP，包含 SKILL.md、脚本、引用和资源文件。',
  '- 本机凭据、.git、node_modules、缓存、日志、数据库、私钥和证书不会进入本包。',
  '- 重复启动会按稳定 ID 更新，不会重复创建 Skill。',
  '',
].join('\n'))

fs.rmSync(targetDir, { recursive: true, force: true })
fs.renameSync(tempDir, targetDir)

const totalFiles = manifest.skills.reduce((sum, skill) => sum + skill.files, 0)
console.log(`已同步 ${manifest.skillCount} 个 Skill、${totalFiles} 个 Skill 文件到 bundled-skills/`)
console.log(`清单：${path.join(targetDir, 'manifest.json')}`)
