/**
 * session-summary.js — Stop Hook
 * 每次對話結束存快照（工作目錄 + git 狀態 + 最近 commits）。
 */
const fs = require('fs');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const { spawnSync } = require('child_process');
let d = '';
process.stdin.on('data', c => d += c);
process.stdin.on('end', () => {
  try {
    const sid = (process.env.CLAUDE_SESSION_ID || crypto.createHash('md5').update(process.cwd()).digest('hex').substring(0, 8)).replace(/[^a-zA-Z0-9_-]/g, '_').substring(0, 64);
    const sessionsDir = path.join(os.homedir(), '.claude', 'sessions');
    if (!fs.existsSync(sessionsDir)) fs.mkdirSync(sessionsDir, { recursive: true });
    let entry = `\n## ${new Date().toLocaleTimeString()} — ${new Date().toLocaleDateString()}\n`;
    entry += `\n**CWD:** ${process.cwd()}\n`;
    try {
      const gs = spawnSync('git', ['status', '--short'], { encoding: 'utf8', timeout: 3000 });
      if (gs.stdout) entry += `\n**Git Status:**\n\`\`\`\n${gs.stdout}\`\`\`\n`;
    } catch (e) {}
    try {
      const gl = spawnSync('git', ['log', '--oneline', '-5'], { encoding: 'utf8', timeout: 3000 });
      if (gl.stdout) entry += `\n**Recent Commits:**\n\`\`\`\n${gl.stdout}\`\`\`\n`;
    } catch (e) {}
    const sessionFile = path.join(sessionsDir, `${new Date().toISOString().split('T')[0]}-${sid}.md`);
    fs.appendFileSync(sessionFile, entry);
  } catch (e) {}
  process.stdout.write(d);
});
