/**
 * Skill candidates. Only generates a real skill file when the same pattern
 * appears across multiple sessions (similarSessionCount >= 3) — one-offs
 * become noise. When the gate isn't met, emits a deferred bundle entry
 * (virtual: true) explaining why.
 *
 * Ported from AgentLens (`src/optimal-files/skills.js`). Pure.
 */

export function generateSkillCandidates(analysis) {
  const a = analysis;
  if (!a.similarSessionCount || a.similarSessionCount < 3) {
    return [{
      path: '(none — pattern needs more sessions)',
      kind: 'skill-candidate-deferred',
      title: 'Skill generation deferred',
      content: '',
      reason: a.similarSessionCount
        ? `Only ${a.similarSessionCount} similar session(s) found. Need >= 3 before DashClaw proposes a skill — one-offs become noise.`
        : 'No similar sessions found yet. Skill generation needs a repeatable pattern across >= 3 sessions.',
      confidence: a.confidence.skillCandidate,
      commitRecommendation: 'review',
      group: 'not_recommended_yet',
      virtual: true,
    }];
  }

  const skillName = inferSkillName(a);
  const slug = `.claude/skills/${skillName}/SKILL.md`;
  const sid = (a.session && a.session.session_uuid) || '?';
  const lines = [];
  lines.push(`---`);
  lines.push(`name: ${skillName}`);
  lines.push(`description: ${describeSkill(a)}`);
  lines.push(`---`);
  lines.push('');
  lines.push(`# ${skillName}`);
  lines.push('');
  lines.push(`## Trigger`);
  lines.push(`Use when ${describeTrigger(a)}.`);
  lines.push('');
  lines.push(`## Files to inspect first`);
  for (const r of a.reads.slice(0, 5)) lines.push(`- \`${r.target}\``);
  lines.push('');
  lines.push(`## Steps`);
  lines.push(`1. Read each file listed above before any edit.`);
  if (a.verificationCommands.length) {
    lines.push(`2. Run \`${a.verificationCommands[0].command}\` to capture the current pass/fail baseline.`);
  } else {
    lines.push(`2. Establish a verification baseline before any edit.`);
  }
  lines.push(`3. Plan the changes — list edits up front.`);
  lines.push(`4. Apply edits in one pass; avoid re-reading the same file >= 3 times.`);
  if (a.verificationCommands.length) {
    lines.push(`5. Re-run \`${a.verificationCommands[0].command}\`; do not declare done until it exits 0.`);
  } else {
    lines.push(`5. Run the project's verification command; do not declare done until it passes.`);
  }
  lines.push('');
  lines.push(`## Verification gates`);
  if (a.verificationCommands.length) {
    lines.push(`- \`${a.verificationCommands[0].command}\` exits 0.`);
  }
  lines.push(`- No new high-confidence repeated-run signals in the session's tool sequence.`);
  lines.push(`- No secret-output guard hits.`);
  lines.push('');
  lines.push(`## What not to do`);
  lines.push(`- Don't introduce new abstractions when an existing one fits.`);
  lines.push(`- Don't add error handling for scenarios that can't happen — only at system boundaries.`);
  lines.push(`- Don't widen scope to a refactor when the trigger calls for a focused change.`);
  lines.push('');
  lines.push(`---`);
  lines.push(`Generated by DashClaw Code Sessions from session \`${sid}\` at \`${a.generatedAt}\`.`);
  lines.push(`Skill candidate distilled from ${a.similarSessionCount} similar prior session(s). Review and edit before relying on it.`);

  return [{
    path: slug,
    kind: 'skill-candidate',
    title: 'Skill candidate (review)',
    content: lines.join('\n') + '\n',
    reason: `${a.similarSessionCount} similar sessions found on this project — pattern qualifies for a skill candidate.`,
    confidence: a.confidence.skillCandidate,
    commitRecommendation: 'review',
    group: 'optional',
  }];
}

export function inferSkillName(a) {
  const slug = (a.project && a.project.slug) || 'project';
  if (a.pathScopes.tests && a.pathScopes.tests.length >= 3) return `${slug.toLowerCase()}-test-iteration`.replace(/[^a-z0-9-]/g, '-');
  if (a.pathScopes.backend && a.pathScopes.backend.length >= 3) return `${slug.toLowerCase()}-route-changes`.replace(/[^a-z0-9-]/g, '-');
  if (a.pathScopes.frontend && a.pathScopes.frontend.length >= 3) return `${slug.toLowerCase()}-ui-iteration`.replace(/[^a-z0-9-]/g, '-');
  return `${slug.toLowerCase()}-session-recipe`.replace(/[^a-z0-9-]/g, '-');
}

function describeSkill(a) {
  if (a.pathScopes.tests && a.pathScopes.tests.length >= 3) return 'Iterate on tests with verification gates.';
  if (a.pathScopes.backend && a.pathScopes.backend.length >= 3) return 'Make focused changes to API routes with verification.';
  if (a.pathScopes.frontend && a.pathScopes.frontend.length >= 3) return 'Iterate on UI changes against a vanilla static frontend.';
  return 'Resume a previously-running task on this project with the right context loaded.';
}

function describeTrigger(a) {
  if (a.pathScopes.tests && a.pathScopes.tests.length >= 3) return 'a change must be verified by the existing test suite';
  if (a.pathScopes.backend && a.pathScopes.backend.length >= 3) return 'an HTTP route or server module needs to be added or changed';
  if (a.pathScopes.frontend && a.pathScopes.frontend.length >= 3) return 'the user-facing surface needs a change';
  return 'the agent is resuming work that was previously interrupted';
}
