'use strict';
// Parse background-task counts and @team-member mentions out of a
// terminal-buffer snapshot. Modeled on ccmanager's Claude Code parser.
//
// Returned shape:
//   {
//     backgroundTasks: <number>,  // running tasks reported by the CLI
//     teamMembers: <number>,      // distinct @name mentions visible
//     teamNames:   ['@alice', '@bob']  // deduped, capped at 10
//   }
//
// Designed to be cheap — pure string regex, no subprocesses, no I/O.
// Callers can run it on every feed-result without measurable overhead.

// Claude Code reports running background tasks as things like:
//   "3 background tasks"
//   "Running 2 background tasks"
//   "1 running · 2 completed"
const BG_TASKS_RE = /\b(\d+)\s+(?:running|background|pending)\s+(?:tasks?|jobs?)\b/i;
// Also the compact Claude Code "⏵ 3 running" indicator.
const BG_RUNNING_RE = /(?:⏵|▶)\s*(\d+)\s+running\b/i;
// ccmanager also detects "N local agents".
const LOCAL_AGENTS_RE = /\b(\d+)\s+local\s+agents?\b/i;

// Team-member mentions: @name where name is [A-Za-z0-9_-]+
// Scoped to a context line (the "shift+↑ to expand" legend).
const TEAM_LINE_RE = /shift\s*\+\s*(?:↑|up|arrow)\s+to\s+expand/i;
const MENTION_RE = /@([A-Za-z][A-Za-z0-9_-]{0,30})/g;

function parseCounters(buffer) {
  const empty = { backgroundTasks: 0, teamMembers: 0, teamNames: [] };
  if (!buffer || typeof buffer !== 'string') return empty;
  if (buffer.length < 8) return empty;

  const lines = buffer.split('\n');
  let backgroundTasks = 0;

  for (const line of lines) {
    if (!backgroundTasks) {
      const m = line.match(BG_TASKS_RE) || line.match(BG_RUNNING_RE) || line.match(LOCAL_AGENTS_RE);
      if (m) backgroundTasks = Math.max(backgroundTasks, parseInt(m[1], 10) || 0);
    }
  }

  // Team-member extraction: look for the expand-legend line; scan +/- 2 lines
  // around it so we catch the "@alice @bob" listing that sometimes renders on
  // the line above the legend.
  const teamSet = new Set();
  for (let i = 0; i < lines.length; i++) {
    if (!TEAM_LINE_RE.test(lines[i])) continue;
    const lo = Math.max(0, i - 2);
    const hi = Math.min(lines.length, i + 3);
    for (let j = lo; j < hi; j++) {
      const line = lines[j];
      let m;
      MENTION_RE.lastIndex = 0;
      while ((m = MENTION_RE.exec(line)) !== null) {
        const name = '@' + m[1];
        teamSet.add(name);
        if (teamSet.size > 10) break;
      }
      if (teamSet.size > 10) break;
    }
    break; // one legend line is enough
  }

  const teamNames = Array.from(teamSet).slice(0, 10);
  return {
    backgroundTasks: backgroundTasks | 0,
    teamMembers: teamNames.length,
    teamNames,
  };
}

module.exports = { parseCounters };
