/**
 * Docker Environment Command
 * Manage environment variables for containers
 */

import { exec } from 'child_process'
import { promisify } from 'util'
import { readFileSync, writeFileSync, existsSync } from 'fs'

const execAsync = promisify(exec)

export interface EnvOptions {
  action: 'list' | 'set' | 'unset' | 'export'
  key?: string
  value?: string
  file?: string
}

export async function handle(args: EnvOptions, context: any): Promise<string> {
  const { action, key, value, file = '.env' } = args

  try {
    switch (action) {
      case 'list':
        return listEnv(file)
      case 'set':
        if (!key || value === undefined) {
          throw new Error('Key and value are required for set action')
        }
        return setEnv(file, key, value)
      case 'unset':
        if (!key) {
          throw new Error('Key is required for unset action')
        }
        return unsetEnv(file, key)
      case 'export':
        return exportEnv(file)
      default:
        throw new Error(`Unknown action: ${action}`)
    }
  } catch (error: any) {
    throw new Error(`Environment management failed: ${error.message}`)
  }
}

function listEnv(file: string): string {
  if (!existsSync(file)) {
    return `# Environment file ${file} does not exist`
  }

  const content = readFileSync(file, 'utf-8')
  return content
}

function setEnv(file: string, key: string, value: string): string {
  let content = ''

  if (existsSync(file)) {
    content = readFileSync(file, 'utf-8')
  }

  // Check if key exists
  const lines = content.split('\n')
  const keyIndex = lines.findIndex(line => line.startsWith(`${key}=`))

  if (keyIndex >= 0) {
    // Update existing key
    lines[keyIndex] = `${key}=${value}`
    content = lines.join('\n')
  } else {
    // Add new key
    content += `${key}=${value}\n`
  }

  writeFileSync(file, content, 'utf-8')
  return `✓ Set ${key} in ${file}`
}

function unsetEnv(file: string, key: string): string {
  if (!existsSync(file)) {
    return `# Environment file ${file} does not exist`
  }

  const content = readFileSync(file, 'utf-8')
  const lines = content.split('\n')
  const filtered = lines.filter(line => !line.startsWith(`${key}=`))

  writeFileSync(file, filtered.join('\n'), 'utf-8')
  return `✓ Unset ${key} from ${file}`
}

function exportEnv(file: string): string {
  if (!existsSync(file)) {
    return `# Environment file ${file} does not exist`
  }

  const content = readFileSync(file, 'utf-8')
  const exportCommands = content
    .split('\n')
    .filter(line => line.trim() && !line.startsWith('#'))
    .map(line => `export ${line}`)
    .join('\n')

  return exportCommands
}

export default { handle }
