// Copyright (C) 2026 Garudex Labs.  All Rights Reserved.
// Caracal, a product of Garudex Labs
//
// Renders committed dev defaults and end-user operator templates from the env schema.

import { envEntries, resolveDefault, type StackMode } from './envSchema.js'

const HEADER = [
  '# Copyright (C) 2026 Garudex Labs.  All Rights Reserved.',
  '# Caracal, a product of Garudex Labs',
  '#',
]

// Renders infra/docker/dev.env: every non-secret schema entry with its dev default,
// one comment line per variable describing the value. Committed and regenerated by CI.
export function renderDevEnv(): string {
  const lines: string[] = []
  lines.push(...HEADER)
  lines.push('# Dev defaults rendered from packages/engine/src/envSchema.ts. Do not edit by hand;')
  lines.push('# run `node packages/engine/scripts/render-dev-env.mjs` after schema changes.')
  lines.push('# Operator overrides live in infra/docker/local.env (gitignored).')
  lines.push('')
  for (const [key, spec] of envEntries()) {
    if (spec.secret) continue
    const value = resolveDefault(spec, 'dev' as StackMode)
    if (value === undefined) continue
    lines.push(`# ${spec.description}`)
    lines.push(`${key}=${value}`)
    lines.push('')
  }
  return lines.join('\n')
}

// Renders the end-user operator template ($CARACAL_HOME/caracal.env): only
// exposed knobs, all commented out so the file documents itself without changing
// any default. Secrets are excluded; pinned vars are excluded (immutable in stable).
export function renderOperatorTemplate(mode: StackMode): string {
  const lines: string[] = []
  lines.push(...HEADER)
  lines.push(`# Operator overrides for the Caracal ${mode} stack.`)
  lines.push('# Every entry below is commented out and shows the built-in default.')
  lines.push('# Uncomment a line and edit the value to override; pinned variables')
  lines.push('# (mode, version, registry) are managed by the release and cannot be set here.')
  lines.push('')
  for (const [key, spec] of envEntries()) {
    if (spec.secret || !spec.exposed) continue
    if (spec.pinned?.includes(mode)) continue
    const value = resolveDefault(spec, mode) ?? ''
    lines.push(`# ${spec.description}`)
    lines.push(`# ${key}=${value}`)
    lines.push('')
  }
  return lines.join('\n')
}

// Returns the canonical path to the committed dev defaults file. The path is
// resolved relative to a repo root so the renderer script can write it.
export function devEnvRelativePath(): string {
  return 'infra/docker/dev.env'
}
