/**
 * Per-project "how to start the next session" recipe at
 * .claude/dashclaw/recipes/<slug>.md.
 *
 * Ported from AgentLens (`src/optimal-files/recipe.js`). Pure.
 */

export function generateRecipe(analysis) {
  const a = analysis;
  const slug = (a.project && a.project.slug) || 'project';
  const sid = (a.session && a.session.session_uuid) || '?';
  const recipeName = `${slug.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'project'}-next-session`;
  const lines = [];
  lines.push(`# Next-session recipe — ${slug}`);
  lines.push('');
  lines.push(`A small playbook for starting the next Claude Code session on this project the way the last one ended.`);
  lines.push('');

  lines.push(`## Recommended starting prompt`);
  lines.push('```text');
  lines.push(buildPrompt(a));
  lines.push('```');
  lines.push('');

  lines.push(`## Files to read first`);
  if (a.reads.length) {
    for (const r of a.reads.slice(0, 5)) lines.push(`- \`${shortPath(r.target)}\``);
  } else {
    lines.push(`- (No standout reads — open the repo's README first.)`);
  }
  lines.push('');

  if (a.reads.length) {
    lines.push(`## Files to skip re-reading unless changed`);
    for (const r of a.reads.slice(0, 5)) lines.push(`- \`${shortPath(r.target)}\` (already in CLAUDE.md / session notes)`);
    lines.push('');
  }

  lines.push(`## Commands to run before editing`);
  if (a.verificationCommands.length) {
    for (const v of a.verificationCommands.slice(0, 3)) lines.push(`- \`${v.command}\``);
  } else {
    lines.push(`- Add a verification command here once the project has one.`);
  }
  lines.push('');

  lines.push(`## Completion criteria`);
  lines.push(`- Touched files compile/parse cleanly.`);
  if (a.verificationCommands.length) {
    lines.push(`- \`${a.verificationCommands[0].command}\` exits 0.`);
  }
  lines.push(`- No new high-confidence repeated-run signals in this session's tool sequence.`);
  lines.push(`- No secret-output guard hits.`);
  lines.push('');

  lines.push(`## Verification gates`);
  if (a.verificationCommands.length) {
    lines.push(`- Run \`${a.verificationCommands[0].command}\` after substantive edits.`);
  }
  lines.push(`- Manually exercise the surface area you touched — automated tests are necessary but not sufficient.`);
  lines.push('');

  lines.push(`---`);
  lines.push(`Generated by DashClaw Code Sessions from session \`${sid}\` at \`${a.generatedAt}\`.`);
  lines.push(`Recipes are for next-session improvement, not permanent repo memory. Edit or delete freely.`);

  return {
    path: `.claude/dashclaw/recipes/${recipeName}.md`,
    kind: 'recipe',
    title: 'Next-session recipe',
    content: lines.join('\n') + '\n',
    reason: 'Quick-start playbook for the next session on this project, derived from what worked / what thrashed last time.',
    confidence: a.confidence.contextGap === 'high' || a.verificationCommands.length ? 'high' : 'medium',
    commitRecommendation: 'gitignore',
    group: 'optional',
  };
}

function buildPrompt(a) {
  const slug = (a.project && a.project.slug) || 'this project';
  const out = [];
  out.push(`Resume work on ${slug}.`);
  out.push('');
  out.push(`Start by reading the root CLAUDE.md (if present) and the previous session note at .claude/dashclaw/session-notes/${a.session && a.session.session_uuid}.md (if present).`);
  if (a.reads.length) {
    out.push('');
    out.push(`Then open these files in order:`);
    for (const r of a.reads.slice(0, 5)) out.push(`  - ${shortPath(r.target)}`);
  }
  if (a.verificationCommands.length) {
    out.push('');
    out.push(`Before making any changes, run: ${a.verificationCommands[0].command}`);
  }
  out.push('');
  out.push(`Avoid: re-reading the same file >=3 times. If you do, stop and update CLAUDE.md or the path rule before continuing.`);
  return out.join('\n');
}

function shortPath(p) {
  if (!p) return '';
  const parts = String(p).split(/[\\/]/);
  if (parts.length <= 4) return p;
  return '.../' + parts.slice(-4).join('/');
}
