'use strict';

/**
 * Creation-workflow CLAUDE.md block (IMPL.md §6.2 — 2f).
 *
 * `sigmap --init` injects this block so an agent reading CLAUDE.md knows the
 * grounded-creation guard-rail workflow exists: scaffold → verify-plan →
 * verify-ai-output → review-pr, orchestrated by `sigmap create`. Idempotent and
 * marker-scoped — it never touches human content or the conventions /
 * auto-generated-signatures blocks. Pure string transforms; zero-dependency,
 * bundle-safe.
 */

const START = '<!-- sigmap-creation-workflow:start -->';
const END = '<!-- sigmap-creation-workflow:end -->';

/** Render the Creation workflow block (including its start/end markers). */
function renderCreationWorkflowBlock() {
  return [
    START,
    '## Creation workflow (SigMap)',
    '',
    'When creating or changing code, run the grounded-creation pipeline so each step is verified against the live index:',
    '',
    '1. **`sigmap scaffold "<name>"`** — propose a convention-matched file/structure (refuses if conventions are inconsistent).',
    '2. **`sigmap verify-plan <plan.md>`** — check the plan against the live index (files/symbols exist, blast radius, scope).',
    '3. **`sigmap verify-ai-output <answer.md>`** — flag fake files/symbols/imports in the generated output (offline).',
    '4. **`sigmap review-pr`** — audit the diff for scope drift, god-node edits, missing tests, and security files.',
    '',
    'Or run all four in one pass with **`sigmap create "<task>"`** (`1/4`…`4/4` numbering, single pass/fail).',
    '',
    '<sub>Generated by `sigmap --init` · refresh by re-running it.</sub>',
    END,
  ].join('\n');
}

/**
 * Inject (or replace) the Creation workflow block in existing CLAUDE.md content.
 * Replaces an existing marked block in place; appends one when absent.
 * Idempotent — never touches content outside the markers.
 * @param {string} existing current file content ('' if new)
 * @param {string} block the block from `renderCreationWorkflowBlock`
 * @returns {string}
 */
function injectCreationWorkflow(existing, block) {
  const src = String(existing || '');
  const startIdx = src.indexOf(START);
  if (startIdx !== -1) {
    const endIdx = src.indexOf(END, startIdx);
    if (endIdx !== -1) {
      return src.slice(0, startIdx) + block + src.slice(endIdx + END.length);
    }
  }
  if (src.trim() === '') return block + '\n';
  const sep = src.endsWith('\n') ? '\n' : '\n\n';
  return src + sep + block + '\n';
}

module.exports = { renderCreationWorkflowBlock, injectCreationWorkflow, START, END };
