const ci = require('miniprogram-ci')
const path = require('path')
const { execSync } = require('child_process')

const projectPath = path.resolve(__dirname, '../dist/build/mp-weixin')
const privateKeyPath = path.resolve('/root/opencode-workspace/微信小程序参数/宇之然AI磁场appid/private.wxf466b3c3bc411ffc.key')
const appid = 'wxf466b3c3bc411ffc'

async function main() {
  const project = new ci.Project({
    appid,
    type: 'miniProgram',
    projectPath,
    privateKeyPath,
    ignores: ['node_modules/**/*'],
  })

  // Bump patch version from git tag: v1.0.16 → 1.0.17
  let version = '1.0.3'
  try {
    const gitTag = execSync('git describe --tags --abbrev=0 2>/dev/null || echo ""', { encoding: 'utf8' }).trim()
    if (gitTag) {
      const base = gitTag.replace(/^v/, '')
      const parts = base.split('.')
      if (parts.length >= 1) {
        parts[parts.length - 1] = String(Number(parts[parts.length - 1]) + 1)
      }
      version = parts.join('.')
    }
  } catch {}

  const now = new Date()
  const desc = `v${version} ${now.toISOString().slice(0, 10)} ${now.toTimeString().slice(0, 5)}`

  console.log(`Uploading: ${projectPath}`)
  console.log(`Version: ${version}`)
  console.log(`Desc: ${desc}`)

  const result = await ci.upload({
    project,
    version,
    desc,
    setting: {
      es6: true,
      minify: true,
      autoPrefixWXSS: true,
    },
    onProgressUpdate: (task) => {
      if (task.status === 'uploading') {
        console.log(`Uploading... ${task.current}/${task.total}`)
      }
    },
  })

  console.log('Upload success!')
  console.log('Result:', JSON.stringify(result, null, 2))
}

main().catch(err => {
  console.error('Upload failed:', err.message)
  process.exit(1)
})
