const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const ora = require('ora')
const inquirer = require('inquirer')

const { getConfig } = require('../lib/config')
const { listCodeLibraries, getCodeLibrary } = require('../lib/api')

function pickExtension(codeType) {
  switch (codeType) {
    case 'tsx':
      return '.tsx'
    case 'ts':
      return '.ts'
    case 'html':
      return '.html'
    case 'js':
      return '.js'
    default:
      return '.jsx'
  }
}

async function templatePullCommand(templateId, opts) {
  try {
    const config = getConfig()
    const appId = opts.appId || config.defaultAppId
    if (!appId) {
      throw new Error('App ID is required. Use --app-id or set default with `bild use`.')
    }

    const spinner = ora(`Looking up ${templateId || '<prompt>'}...`).start()
    const all = await listCodeLibraries(appId)
    const items = Array.isArray(all) ? all : Object.values(all || {})

    let lib
    if (templateId) {
      lib = items.find((l) => l.templateId === templateId || l.snippetId === templateId)
      if (!lib) {
        spinner.fail(`Template ${templateId} not found in ${appId}`)
        process.exit(1)
      }
    } else {
      spinner.stop()
      const choices = items
        .map((l) => ({
          name: `${l.templateId || l.snippetId} - ${l.name || ''}`,
          value: l,
        }))
        .filter((c) => c.value.templateId || c.value.snippetId)
      const { selected } = await inquirer.createPromptModule()([
        { type: 'list', name: 'selected', message: 'Select a template to pull:', choices },
      ])
      lib = selected
      spinner.start('Fetching source...')
    }

    const full = await getCodeLibrary(appId, lib.id || lib.cid || lib.codeLibraryId)
    const rawCode = full?.code?.raw || full?.code || lib.code?.raw || lib.code
    const codeType = full?.codeType || lib.codeType || 'jsx'

    if (!rawCode || typeof rawCode !== 'string') {
      spinner.fail('Remote template did not return source')
      process.exit(1)
    }

    const ext = pickExtension(codeType)
    const outPath = path.resolve(
      opts.out || `${lib.templateId || lib.snippetId || templateId}${ext}`
    )
    fs.writeFileSync(outPath, rawCode, 'utf8')
    spinner.succeed(`Wrote ${outPath}`)
    console.log(chalk.blue('Next: edit locally, then `bild library update <file>` to publish.'))
  } catch (error) {
    console.error(chalk.red(`\ntemplate pull failed: ${error.message}`))
    process.exit(1)
  }
}

module.exports = templatePullCommand
