'use strict';

/**
 * CLAUDE.md convention injection (IMPL.md §7 Phase 2 / §8 step 5).
 *
 * Renders the conventions detected by `extractConventions` into a
 * marker-delimited markdown block and injects it into CLAUDE.md so an agent
 * reading the file plans grounded in the repo's house style. Idempotent and
 * marker-scoped — it never touches human content or the `## Auto-generated
 * signatures` block. Pure string transforms; zero-dependency, bundle-safe.
 */

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

const TIER_NOTE = {
  consistent: 'consistent — match it',
  mostly: 'dominant, with some drift',
  inconsistent: 'no clear convention — check neighboring files',
};

const NAMES = {
  fileNaming: 'File naming',
  exportStyle: 'Export style',
};

const _pct = (n) => `${Math.round(n * 100)}%`;

function _conventionLine(label, conv) {
  if (!conv || conv.total === 0 || !conv.dominant) return null;
  const note = TIER_NOTE[conv.tier] || conv.tier;
  let line = `- **${label}:** ${conv.dominant} (${_pct(conv.dominantPct)} — ${note}).`;
  const others = conv.variants.slice(1).filter((v) => v.pct > 0);
  if (others.length) {
    line += ` Variants: ${others.map((v) => `${v.label} ${_pct(v.pct)}`).join(', ')}.`;
  }
  return line;
}

/**
 * Render the conventions block (including its start/end markers).
 * @param {object} result an `extractConventions` result
 * @param {string} [version] SigMap version for the footer
 * @returns {string}
 */
function renderConventionsBlock(result, version) {
  const lines = [];
  for (const key of ['fileNaming', 'exportStyle']) {
    const l = _conventionLine(NAMES[key], result && result[key]);
    if (l) lines.push(l);
  }
  if (result && result.testFramework) {
    lines.push(`- **Test framework:** ${result.testFramework}.`);
  }

  const body = lines.length
    ? lines
    : ['- No conventions detected yet (run `sigmap conventions` on a TS/JS/Python repo).'];

  const ver = version ? ` v${version}` : '';
  return [
    START,
    '## Conventions (auto-detected by SigMap)',
    '',
    'Match these when writing or editing code (TS/JS/Python):',
    '',
    ...body,
    '',
    `<sub>Generated by SigMap${ver} · run \`sigmap conventions --inject\` to refresh.</sub>`,
    END,
  ].join('\n');
}

/**
 * Inject (or replace) the conventions 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 the file is new)
 * @param {string} block the block returned by `renderConventionsBlock`
 * @returns {string}
 */
function injectConventions(existing, block) {
  const src = String(existing || '');
  const startIdx = src.indexOf(START);
  if (startIdx !== -1) {
    const endIdx = src.indexOf(END, startIdx);
    if (endIdx !== -1) {
      const before = src.slice(0, startIdx);
      const after = src.slice(endIdx + END.length);
      return before + block + after;
    }
  }
  if (src.trim() === '') return block + '\n';
  const sep = src.endsWith('\n') ? '\n' : '\n\n';
  return src + sep + block + '\n';
}

module.exports = { renderConventionsBlock, injectConventions, START, END };
