#!/usr/bin/env node

import path from 'node:path'
import { fileURLToPath } from 'node:url'

import {
  buildRuntimeReadinessReport,
  deriveHealthBaseUrl,
  fetchLiveAuthHealth,
  fetchLiveReleaseManifest,
  fetchLiveWebsiteShell,
  formatRuntimeReadinessReport,
  loadEnvFile,
} from './runtime-readiness-lib.mjs'

function parseArgs(argv) {
  const options = {
    frontendEnv: '',
    serverEnv: '',
    healthUrl: '',
    skipLiveHealth: false,
    deploymentTier: '',
    json: false,
  }

  for (let index = 0; index < argv.length; index += 1) {
    const argument = argv[index]
    if (argument === '--frontend-env') {
      options.frontendEnv = argv[index + 1] || ''
      index += 1
      continue
    }
    if (argument === '--server-env') {
      options.serverEnv = argv[index + 1] || ''
      index += 1
      continue
    }
    if (argument === '--health-url') {
      options.healthUrl = argv[index + 1] || ''
      index += 1
      continue
    }
    if (argument === '--skip-live-health') {
      options.skipLiveHealth = true
      continue
    }
    if (argument === '--deployment-tier') {
      options.deploymentTier = argv[index + 1] || ''
      index += 1
      continue
    }
    if (argument === '--json') {
      options.json = true
    }
  }

  return options
}

const currentFile = fileURLToPath(import.meta.url)
const websiteRoot = path.resolve(path.dirname(currentFile), '..')
const args = parseArgs(process.argv.slice(2))

const frontendEnvFile = loadEnvFile(args.frontendEnv || path.join(websiteRoot, '.env'))
const serverEnvFile = loadEnvFile(args.serverEnv || path.join(websiteRoot, 'server', '.env'))

let preloadFailures = []
if (!frontendEnvFile.exists) {
  preloadFailures.push(`Frontend env file not found: ${frontendEnvFile.path}`)
}
if (!serverEnvFile.exists) {
  preloadFailures.push(`Server env file not found: ${serverEnvFile.path}`)
}

const healthBaseUrl = deriveHealthBaseUrl({
  explicitHealthUrl: args.healthUrl,
  frontendEnv: frontendEnvFile.values,
  serverEnv: serverEnvFile.values,
})

let liveHealth = null
let liveReleaseManifest = null
let liveWebsiteShell = null
let liveHealthAttempted = false
let liveReleaseManifestAttempted = false
let liveWebsiteShellAttempted = false
if (!args.skipLiveHealth && healthBaseUrl) {
  try {
    liveHealthAttempted = true
    liveHealth = await fetchLiveAuthHealth(healthBaseUrl)
  } catch (error) {
    preloadFailures.push(`Live auth health check failed: ${error instanceof Error ? error.message : String(error)}`)
  }

  try {
    liveReleaseManifestAttempted = true
    liveReleaseManifest = await fetchLiveReleaseManifest(healthBaseUrl)
  } catch (error) {
    preloadFailures.push(`Live release manifest check failed: ${error instanceof Error ? error.message : String(error)}`)
  }

  try {
    liveWebsiteShellAttempted = true
    liveWebsiteShell = await fetchLiveWebsiteShell(healthBaseUrl)
  } catch (error) {
    preloadFailures.push(`Live website shell check failed: ${error instanceof Error ? error.message : String(error)}`)
  }
}

const report = buildRuntimeReadinessReport({
  frontendEnv: frontendEnvFile.values,
  serverEnv: serverEnvFile.values,
  liveHealth,
  liveReleaseManifest,
  liveWebsiteShell,
  liveHealthAttempted,
  liveReleaseManifestAttempted,
  liveWebsiteShellAttempted,
  frontendEnvPath: frontendEnvFile.path,
  serverEnvPath: serverEnvFile.path,
  healthBaseUrl,
  deploymentTier: args.deploymentTier,
})

if (preloadFailures.length > 0) {
  report.failures.unshift(...preloadFailures)
  report.ok = false
}

if (args.json) {
  process.stdout.write(`${JSON.stringify(report, null, 2)}\n`)
} else {
  process.stdout.write(formatRuntimeReadinessReport(report))
}

process.exitCode = report.ok ? 0 : 1
