'use strict';

/**
 * Copilot adapter — writes to .github/copilot-instructions.md
 * GitHub Copilot reads this file automatically in every workspace.
 *
 * Contract:
 *   format(context, opts?) → string
 *   outputPath(cwd) → string
 */

const path = require('path');
const fs = require('fs');

const name = 'copilot';
const MARKER = '\n\n## Auto-generated signatures\n<!-- Updated by gen-context.js -->\n';

/**
 * Format context for GitHub Copilot instructions.
 * @param {string} context - Raw signature context string
 * @param {object} [opts]
 * @param {string} [opts.version] - SigMap version string
 * @returns {string}
 */
function format(context, opts = {}) {
  if (!context || typeof context !== 'string') return '';
  const version   = opts.version   || 'unknown';
  const timestamp = new Date().toISOString();
  const meta = _confidenceMeta(opts);
  const header = [
    `<!-- Generated by SigMap gen-context.js v${version} -->`,
    `<!-- Updated: ${timestamp} -->`,
    meta,
    `<!-- Do not edit below — regenerate with: node gen-context.js -->`,
    '',
    '## SigMap commands',
    '',
    '| When | Command |',
    '|------|---------|',
    '| Before answering a question about code | `sigmap ask "<your question>"` |',
    '| After changing config or source dirs | `sigmap validate` |',
    '| To verify an AI answer is grounded | `sigmap judge --response <file>` |',
    '',
    '# Code signatures',
    '',
  ].join('\n');
  return header + context;
}

function _confidenceMeta(opts) {
  const parts = [`version=${opts.version || 'unknown'}`];
  if (opts.confidence)    parts.push(`confidence=${opts.confidence}`);
  if (opts.coverage != null) parts.push(`coverage=${opts.coverage}%`);
  if (opts.dropped  != null) parts.push(`dropped=${opts.dropped}`);
  if (opts.commit)        parts.push(`commit=${opts.commit}`);
  return `<!-- sigmap: ${parts.join(' ')} -->`;
}

/**
 * Return the output file path for this adapter.
 * @param {string} cwd - Project root
 * @returns {string}
 */
function outputPath(cwd) {
  return path.join(cwd, '.github', 'copilot-instructions.md');
}

/**
 * Write signatures into copilot-instructions.md using append-under-marker.
 * If marker exists, content above marker is preserved.
 * If legacy generated content exists without marker, replace it cleanly.
 * @param {string} context - Raw signature context string
 * @param {string} cwd - Project root
 * @param {object} [opts]
 */
function write(context, cwd, opts = {}) {
  const filePath = outputPath(cwd);
  let existing = '';
  if (fs.existsSync(filePath)) {
    existing = fs.readFileSync(filePath, 'utf8');
  }

  const formatted = format(context, opts);
  const markerIdx = existing.indexOf('## Auto-generated signatures');

  let newContent;
  if (markerIdx !== -1) {
    newContent = existing.slice(0, markerIdx) + MARKER.trimStart() + formatted;
  } else {
    const isLegacyGenerated = existing.includes('<!-- Generated by SigMap gen-context.js')
      || existing.includes('# Code signatures');
    newContent = isLegacyGenerated
      ? MARKER.trimStart() + formatted
      : existing + MARKER + formatted;
  }

  fs.mkdirSync(path.dirname(filePath), { recursive: true });
  fs.writeFileSync(filePath, newContent, 'utf8');
}

module.exports = { name, format, outputPath, write };
