// Copyright 2026 Cisco Systems, Inc. and its affiliates
// SPDX-License-Identifier: Apache-2.0
//
// Render the operator-facing install script. Each emitted file is
// dropped on disk via a heredoc so the script is fully self-contained
// (no curl, no scp). The operator can audit every byte before running.
//
// Output is bash. We deliberately avoid here-strings or printf so the
// produced script reads cleanly when copy-pasted into an editor.

import type { Policy } from '../types';
import { emit } from './emit';

const HEADER = `#!/usr/bin/env bash
# DefenseClaw policy install script — generated by docs-site policy creator.
# Inspect every heredoc below before running. Re-run is idempotent.
set -euo pipefail

POLICIES_ROOT="\${HOME}/.defenseclaw/policies"
mkdir -p "\${POLICIES_ROOT}"
`;

const FOOTER = (name: string) => `
# Activate the new policy.
defenseclaw policy activate "${name}"
echo
echo "Activated policy: ${name}"
`;

// Strip the leading "~/.defenseclaw/policies/" path prefix that emit()
// produces; the bash script uses POLICIES_ROOT instead.
function relPath(path: string): string {
  return path.replace(/^~\/\.defenseclaw\/policies\//, '');
}

// Quote a heredoc delimiter so the shell doesn't expand $vars / `cmd`
// inside the body. The wrapper uses a randomised delimiter to avoid
// collisions with any literal "EOF" the operator authored in their
// rule descriptions.
function heredoc(target: string, body: string): string {
  const delim = `DC_EOF_${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
  return `mkdir -p "$(dirname "${target}")"
cat > "${target}" <<'${delim}'
${body.trimEnd()}
${delim}
echo "  wrote ${target}"
`;
}

export function emitInstallScript(policy: Policy): string {
  const files = emit(policy);
  const body = files
    .map((f) => {
      const rel = relPath(f.path);
      return `# ${f.description}\n${heredoc(`\${POLICIES_ROOT}/${rel}`, f.contents)}`;
    })
    .join('\n');
  return `${HEADER}\n${body}\n${FOOTER(policy.name)}`;
}

export function emitTarball(): string {
  // Operators occasionally want the same files as a tarball they can
  // store in their config repo. We expose a stub here so the bottom bar
  // can offer it as an option later — full implementation lands when an
  // operator actually asks for it (the install script covers the same
  // use case today).
  return '';
}
