const { displayToken } = require('../lib/auth')
const chalk = require('chalk')

function detectShell() {
  const shell = process.env.SHELL || ''
  
  if (shell.includes('fish')) {
    return 'fish'
  }
  
  if (shell.includes('zsh')) {
    return 'zsh'
  }
  
  if (shell.includes('bash')) {
    return 'bash'
  }
  
  if (process.platform === 'win32') {
    if (process.env.PSModulePath) {
      return 'powershell'
    }
    return 'cmd'
  }
  
  return 'bash'
}

function getExportCommand(tokenValue, shell) {
  switch (shell) {
    case 'fish':
      return `set -x BILD_TOKEN "${tokenValue}"`
    case 'powershell':
      return `$env:BILD_TOKEN="${tokenValue}"`
    case 'cmd':
      return `set BILD_TOKEN=${tokenValue}`
    default:
      return `export BILD_TOKEN="${tokenValue}"`
  }
}

async function tokenCommand(options = {}) {
  try {
    const tokenInfo = await displayToken()
    
    if (!tokenInfo.token) {
      console.error(chalk.red('No token found'))
      console.log(chalk.yellow('\nTo authenticate:'))
      console.log(chalk.yellow('  - Run: bild login'))
      console.log(chalk.yellow('  - Or: bild token set   (paste token; stored in keychain)'))
      console.log(chalk.yellow('  - Or set BILD_TOKEN or CMS_TOKEN environment variable'))
      process.exit(1)
    }
    
    if (options.source) {
      console.log(chalk.blue('Token source:'), tokenInfo.source)
      return
    }
    
    if (options.validate) {
      if (tokenInfo.isValid) {
        console.log(chalk.green('✓ Token is valid (JWT format)'))
      } else {
        console.log(chalk.red('✗ Token is invalid (not a valid JWT format)'))
        process.exit(1)
      }
      return
    }
    
    if (options.export) {
      const shell = detectShell()
      const exportCmd = getExportCommand(tokenInfo.token, shell)
      
      console.log(chalk.blue(`Detected shell: ${shell}`))
      console.log(chalk.yellow('\nCopy and run this command:'))
      console.log(chalk.green(exportCmd))
      console.log('')
      console.log(chalk.dim('Or copy the token directly:'))
      console.log(chalk.dim(tokenInfo.token))
      return
    }
    
    console.log(chalk.blue('Current token:'))
    console.log(tokenInfo.token)
    console.log('')
    console.log(chalk.dim(`Source: ${tokenInfo.source}`))
    console.log(chalk.dim(`Valid: ${tokenInfo.isValid ? 'Yes' : 'No'}`))
  } catch (error) {
    console.error(chalk.red(`Error: ${error.message}`))
    process.exit(1)
  }
}

module.exports = tokenCommand
