'use strict';
const path = require('path');
const fs   = require('fs');
const { tryGit } = require('../util/git');
module.exports = { format, outputPath };

function outputPath(cwd) { return path.join(cwd, 'llms.txt'); }

function getShortCommit(cwd) {
  return tryGit(['rev-parse', '--short', 'HEAD'], { cwd, timeout: 2000 });
}

function detectVersion(cwd) {
  try {
    const pkg = path.join(cwd, 'package.json');
    if (fs.existsSync(pkg)) return JSON.parse(fs.readFileSync(pkg, 'utf8')).version || '';
  } catch (_) {}
  return '';
}

function format(context, cwd, writtenFiles, sigmapVersion) {
  writtenFiles  = writtenFiles  || [];
  sigmapVersion = sigmapVersion || '';

  const name   = context.projectName || path.basename(cwd);
  const ver    = detectVersion(cwd);
  const commit = getShortCommit(cwd);
  const langs  = [...new Set((context.fileEntries || []).map(f => f.language).filter(Boolean))];

  const lines = [
    '# SigMap Context Index',
    `> Generated by SigMap v${sigmapVersion} — the deterministic, verifiable grounding layer for AI code work`,
    '',
    '## Project',
    `- Name: ${name}`,
  ];
  if (ver)          lines.push(`- Version: ${ver}`);
  if (langs.length) lines.push(`- Language: ${langs.join(', ')}`);
  if (commit)       lines.push(`- Commit: ${commit}`);

  if (writtenFiles.length) {
    lines.push('', '## Context Files');
    for (const f of writtenFiles) {
      const rel   = path.relative(cwd, f.path);
      const extra = f.tokens ? `: ${f.tokens} tokens` : '';
      lines.push(`- [${f.label || rel}](${rel})${extra}`);
    }
  }

  const mods = context.srcDirs || [];
  if (mods.length) {
    lines.push('', '## Source Modules');
    for (const m of mods) lines.push(`- [${m}/](${m}/)`);
  }

  const top5 = (context.fileEntries || [])
    .sort((a, b) => (b.sigs || []).length - (a.sigs || []).length)
    .slice(0, 5);
  if (top5.length) {
    lines.push('', '## Key Files');
    for (const f of top5) {
      const rel     = path.relative(cwd, f.filePath);
      const preview = (f.sigs || []).slice(0, 3).join(', ');
      lines.push(`- ${rel}: ${preview}`);
    }
  }

  return lines.join('\n');
}
