/**
 * Docker Logs Command
 * View and filter container logs
 */

import { exec } from 'child_process'
import { promisify } from 'util'

const execAsync = promisify(exec)

export interface LogsOptions {
  service?: string
  tail?: number
  follow?: boolean
  since?: string
  grep?: string
}

export async function handle(args: LogsOptions, context: any): Promise<string> {
  const { service, tail = 100, follow = false, since, grep } = args

  try {
    let command = 'docker-compose logs'

    if (tail) {
      command += ` --tail ${tail}`
    }

    if (follow) {
      command += ' -f'
    }

    if (since) {
      command += ` --since "${since}"`
    }

    if (service) {
      command += ` ${service}`
    }

    const { stdout, stderr } = await execAsync(command)

    let logs = stdout

    // Filter by grep pattern if provided
    if (grep) {
      const lines = logs.split('\n')
      const filtered = lines.filter(line => line.includes(grep))
      logs = filtered.join('\n')
    }

    return logs || stderr || 'No logs found'
  } catch (error: any) {
    throw new Error(`Failed to fetch logs: ${error.message}`)
  }
}

export default { handle }
