import { Command } from 'commander'
import { createRequire } from 'node:module'
import { initCommand } from './commands/init.js'
import { buildCommand } from './commands/build.js'
import { pushCommand } from './commands/push.js'
import { issuesCommand } from './commands/issues.js'
import { testCommand } from './commands/test.js'
import { connectCommand } from './commands/connect.js'
import { docsCommand } from './commands/docs.js'
import { logsCommand } from './commands/logs.js'
import { skillsCommand } from './commands/skills.js'
import { trackCliEvent, findGameDir, getOrCreateProjectId, setupProjectCustomizations } from './telemetry.js'

// Read the installed package's version so `merels --version` matches npm.
const require = createRequire(import.meta.url)
const { version } = require('../package.json') as { version: string }

const program = new Command()

program
  .name('merels')
  .description('Creator CLI toolchain to bootstrap, build, and push games on Merels')
  .version(version)

program.hook('preAction', async (thisCommand, actionCommand) => {
  const commandName = actionCommand.name()
  if (commandName === 'connect') return

  // 1. Verify and auto-heal project customizations
  try {
    const cwd = process.cwd()
    const gameDir = await findGameDir(cwd)
    if (gameDir) {
      const { projectId, folderId } = await getOrCreateProjectId(gameDir)
      await setupProjectCustomizations(gameDir, projectId, folderId)
    }
  } catch {}

  // 2. Track CLI command execution
  try {
    const args = actionCommand.args
    const opts = actionCommand.opts()
    await trackCliEvent(commandName, args, opts)
  } catch {}
})

program.addCommand(initCommand)
program.addCommand(buildCommand)
program.addCommand(pushCommand)
program.addCommand(issuesCommand)
program.addCommand(testCommand)
program.addCommand(connectCommand)
program.addCommand(docsCommand)
program.addCommand(logsCommand)
program.addCommand(skillsCommand)

program.parse(process.argv)

