'use strict';

/**
 * Codex adapter — writes OpenAI-style context to AGENTS.md.
 *
 * This adapter reuses the same prompt format as the OpenAI adapter,
 * but targets AGENTS.md so Codex-style agents can read repository guidance.
 *
 * Contract:
 *   format(context, opts?) → string
 *   outputPath(cwd) → string
 *   write(context, cwd, opts?) → void
 */

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

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

const TOOLS_BLOCK = [
  '## Tools',
  '',
  TOOLS_MARKER,
  '',
  '```json',
  JSON.stringify([
    {
      name: 'sigmap_ask',
      description: 'Rank source files by relevance to a natural-language query. Run before exploring the codebase.',
      command: 'sigmap ask "$QUERY"',
    },
    {
      name: 'sigmap_validate',
      description: 'Validate SigMap config and measure context coverage. Run after changing config or source dirs.',
      command: 'sigmap validate',
    },
    {
      name: 'sigmap_judge',
      description: 'Score an LLM response for groundedness against source context. Use to verify answer quality.',
      command: 'sigmap judge --response "$RESPONSE" --context "$CONTEXT"',
    },
    {
      name: 'sigmap_query',
      description: 'Rank all files by relevance using TF-IDF and write a focused mini-context.',
      command: 'sigmap --query "$QUERY" --context',
    },
    {
      name: 'sigmap_weights',
      description: 'Show learned file-ranking multipliers accumulated from past sessions.',
      command: 'sigmap weights',
    },
  ], null, 2),
  '```',
  '',
].join('\n');

/**
 * Format context for AGENTS.md — clean markdown, no LLM preamble.
 * @param {string} context - Raw signature context string
 * @param {object} [opts]
 * @returns {string}
 */
function format(context, opts = {}) {
  if (!context || typeof context !== 'string' || !context.trim()) return '';
  const toolBlock = [
    '## SigMap commands',
    '',
    '| When | Command |',
    '|------|---------|',
    '| Before answering a question | `sigmap ask "<your question>"` |',
    '| After code changes | `sigmap validate` |',
    '| To query by topic | `sigmap --query "<topic>"` |',
    '',
    'Always run `sigmap ask` or `sigmap --query` before searching for files relevant to a task.',
    '',
  ].join('\n');
  return `# Code signatures\n\n${toolBlock}${context}`;
}

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

/**
 * Write signatures into AGENTS.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')
      || existing.includes('# Code signatures');
    newContent = isLegacyGenerated
      ? MARKER.trimStart() + formatted
      : existing + MARKER + formatted;
  }

  // Inject ## Tools block above the sig marker if not already present
  if (!newContent.includes(TOOLS_MARKER)) {
    const sigMarkerPos = newContent.indexOf('## Auto-generated signatures');
    if (sigMarkerPos !== -1) {
      newContent = newContent.slice(0, sigMarkerPos) + TOOLS_BLOCK + '\n' + newContent.slice(sigMarkerPos);
    } else {
      newContent = TOOLS_BLOCK + '\n' + newContent;
    }
  }

  fs.writeFileSync(filePath, newContent, 'utf8');
}

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