// Brain-retro #5 candidate C, hole 8: override-usage monitor.
//
// Reads override-usage.jsonl (one JSON line per override invocation:
// {ts, session_id, rule, phrase}) and produces a STATUS.md block with
// per-phrase totals + today's count. Warns when any phrase exceeds
// threshold/day (default 5).
//
// Pure — takes raw log string + opts, returns markdown.

export function computeOverrideUsageBlock(rawLog, opts = {}) {
  const now = opts.now ? new Date(opts.now) : new Date();
  const today = now.toISOString().slice(0, 10);
  const threshold = opts.threshold ?? 5;

  if (!rawLog || typeof rawLog !== 'string') {
    return `## Использование override-фраз\n\nНе использовалось.`;
  }

  const lines = rawLog.split('\n').filter(Boolean);
  if (lines.length === 0) {
    return `## Использование override-фраз\n\nНе использовалось.`;
  }

  const todayCounts = {};
  const allCounts = {};
  for (const l of lines) {
    let e;
    try { e = JSON.parse(l); } catch { continue; }
    if (!e || typeof e.phrase !== 'string' || !e.phrase) continue;
    allCounts[e.phrase] = (allCounts[e.phrase] || 0) + 1;
    if (typeof e.ts === 'string' && e.ts.slice(0, 10) === today) {
      todayCounts[e.phrase] = (todayCounts[e.phrase] || 0) + 1;
    }
  }

  if (Object.keys(allCounts).length === 0) {
    return `## Использование override-фраз\n\nНе использовалось.`;
  }

  const sorted = Object.entries(allCounts).sort((a, b) => b[1] - a[1]);
  const rows = sorted.map(([phrase, total]) => {
    const tCount = todayCounts[phrase] || 0;
    const warn = tCount >= threshold ? ' ⚠️' : '';
    return `| \`${phrase}\` | ${total} | ${tCount}${warn} |`;
  }).join('\n');

  const anyWarn = Object.values(todayCounts).some((v) => v >= threshold);
  const header = anyWarn ? `⚠️ Превышен порог override-использования сегодня (≥${threshold}/день)` : '';

  return `## Использование override-фраз

${header}

| Фраза | За всё время | За сегодня |
|---|---|---|
${rows}`;
}
