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

import { REQUIRED_NODE_MAJOR, isReleaseExcluded, parseNodeMajor } from './student-release-utils.mjs'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')

const requiredFiles = [
  'package.json',
  'package-lock.json',
  'README.md',
  'START-HERE.md',
  'ENVIRONMENT.md',
  'README-STUDENT.md',
  'AI-CODING-PROMPT.md',
  'CLOUDFLARE-STUDENT.md',
  'src/App.jsx',
  'cf-worker/package.json',
  'cf-worker/package-lock.json',
  'cf-worker/server.js',
  'cf-worker/src/index.js',
  'cf-worker/src/cloudflare-lite.js',
  'cf-worker/migrations/0001_init.sql',
  'cf-worker/migrations/0014_local_runtime_agents.sql',
  'cf-worker/migrations/0017_local_runtime_student_presets.sql',
  'cf-worker/migrations/0018_qoder_cloud_agent_runtime.sql',
  'cf-worker/migrations/0019_direct_skill_create.sql',
  'cf-worker/migrations/0020_unified_runtime_streaming.sql',
  'cf-worker/seed/categories.sql',
  'scripts/runtime-presets.mjs',
  'scripts/aipros-auto-start.mjs',
  'scripts/aipros-runtime-setup.mjs',
  'scripts/apply-local-runtime-patch.mjs',
  'scripts/bundle-local-skills.mjs',
  'scripts/bundled-skills-utils.mjs',
  'cf-worker/scripts/bundled-skills-import.cjs',
  'bundled-skills/manifest.json',
]

function check(condition, ok, fail, failures) {
  if (condition) {
    console.log(`✓ ${ok}`)
  } else {
    console.log(`✗ ${fail}`)
    failures.push(fail)
  }
}

function commandExists(command) {
  const result = spawnSync(command, ['--version'], {
    cwd: rootDir,
    stdio: 'ignore',
    shell: process.platform === 'win32',
  })
  return result.status === 0
}

const failures = []
const warnings = []

console.log('AIPROS Lite 学员包检查\n')

const nodeMajor = parseNodeMajor(process.version)
check(
  nodeMajor >= REQUIRED_NODE_MAJOR,
  `Node.js ${process.version} 满足要求`,
  `Node.js ${process.version} 过低，需要 ${REQUIRED_NODE_MAJOR}+`,
  failures,
)
check(commandExists('npm'), 'npm 可用', 'npm 不可用，请安装 Node.js LTS', failures)

for (const file of requiredFiles) {
  check(fs.existsSync(path.join(rootDir, file)), `存在 ${file}`, `缺少 ${file}`, failures)
}

const bundledManifestPath = path.join(rootDir, 'bundled-skills', 'manifest.json')
if (fs.existsSync(bundledManifestPath)) {
  const manifest = JSON.parse(fs.readFileSync(bundledManifestPath, 'utf8'))
  check(
    Number(manifest.skillCount) === 184 && manifest.skills?.length === 184,
    '内置 Skill 清单包含 184 个完整 Skill',
    `内置 Skill 数量异常：期望 184，实际 ${manifest.skillCount || 0}`,
    failures,
  )
}

const sensitiveFiles = [
  'deploy/ssl/zhenyuskill.com.key',
  'deploy/ssl/zhenyuskill.com.pem',
  'deploy/cert.zip',
].filter(file => fs.existsSync(path.join(rootDir, file)))

for (const file of sensitiveFiles) {
  if (isReleaseExcluded(file)) {
    warnings.push(`${file} 存在于源码目录，但 release 打包脚本会排除它`)
  } else {
    failures.push(`${file} 未被 release 排除规则覆盖`)
  }
}

if (fs.existsSync(path.join(rootDir, 'node_modules'))) {
  warnings.push('根目录 node_modules 存在，release 打包脚本会排除它')
}
if (fs.existsSync(path.join(rootDir, 'cf-worker/node_modules'))) {
  warnings.push('cf-worker/node_modules 存在，release 打包脚本会排除它')
}

if (warnings.length) {
  console.log('\n提示：')
  for (const warning of warnings) console.log(`! ${warning}`)
}

if (failures.length) {
  console.log('\n检查未通过：')
  for (const failure of failures) console.log(`- ${failure}`)
  process.exit(1)
}

console.log('\n检查通过。可以运行 npm run local 或 npm run package:student。')
