#!/usr/bin/env node

import { execSync } from "child_process"
import chalk from "chalk"

// Get configuration from command line arguments
const config = JSON.parse(process.argv[2])
const {
  command,
  isModernCompose,
  projectName,
  dockerComposePath,
  servicesToStart,
  serviceConfigs,
} = config

const checkServices = async () => {
  for (const service of servicesToStart) {
    try {
      const psCommand = isModernCompose
        ? `"${command}" compose -p "${projectName}" ps --format json "${service}"`
        : `"${command}" -p "${projectName}" ps --format json "${service}"`

      const result = execSync(psCommand, { stdio: "pipe", encoding: "utf8" })
      const lines = result
        .trim()
        .split("\n")
        .filter((line) => line.trim())

      if (lines.length > 0) {
        const serviceInfo = JSON.parse(lines[0])
        const status = serviceInfo.State || serviceInfo.status || "unknown"

        if (status === "exited" || status === "dead") {
          console.error(
            chalk.red(
              `❌ Service ${service} has failed with status: ${status}`,
            ),
          )

          // Show recent logs for the failed service
          const logsCommand = isModernCompose
            ? `"${command}" compose -p "${projectName}" -f "${dockerComposePath}" logs --tail 50 "${service}"`
            : `"${command}" -p "${projectName}" -f "${dockerComposePath}" logs --tail 50 "${service}"`

          console.log(
            chalk.yellow(`\n🔍 Recent logs for failed service ${service}:`),
          )
          console.log(chalk.gray("─".repeat(80)))

          try {
            const logs = execSync(logsCommand, {
              stdio: "pipe",
              encoding: "utf8",
            })

            if (logs.trim()) {
              console.log(logs)
            } else {
              console.log(chalk.yellow("No logs available"))
            }
          } catch (logError) {
            console.error(chalk.red(`Failed to get logs: ${logError.message}`))
          }

          console.log(chalk.gray("─".repeat(80)))
          process.exit(1) // Exit monitoring to signal failure
        }
      }
    } catch (error) {
      // Ignore temporary errors during status checks
      // This can happen if services are still starting up
    }
  }
}

// Check every 3 seconds
const interval = setInterval(checkServices, 3000)

// Clean shutdown handlers
process.on("SIGTERM", () => {
  clearInterval(interval)
  process.exit(0)
})

process.on("SIGINT", () => {
  clearInterval(interval)
  process.exit(0)
})

// Initial message
console.log(chalk.blue(`🔍 Monitoring services: ${servicesToStart.join(", ")}`))
