"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatePlaybook = generatePlaybook;
exports.getPlaybook = getPlaybook;
exports.listPlaybooks = listPlaybooks;
exports.getPlaybooksDir = getPlaybooksDir;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const PLAYBOOKS_DIR = path.join(os.homedir(), '.fivo', 'cell', 'playbooks');
function ensureDir() {
    if (!fs.existsSync(PLAYBOOKS_DIR))
        fs.mkdirSync(PLAYBOOKS_DIR, { recursive: true });
}
function playbookPath(projectId) {
    return path.join(PLAYBOOKS_DIR, `${projectId.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`);
}
function generatePlaybook(projectId, profile) {
    ensureDir();
    const topPatternsDesc = profile.topPatterns.slice(0, 5).map((p) => p.description).join(', ');
    const overview = `# ${profile.name} — Project Playbook

Generated: ${new Date().toISOString()}
Primary Language: ${profile.primaryLanguage}
Total Patterns: ${profile.totalPatterns}
Average Confidence: ${(profile.averageConfidence * 100).toFixed(0)}%

## Summary
This playbook captures the coding patterns and conventions detected in **${profile.name}**. 
Use it to onboard new team members and maintain consistency across the project.
`;
    const conventionsSection = {
        title: 'Coding Conventions',
        content: `## Detected Conventions

### Language Distribution
${profile.languages.map((l) => `- **${l.language}**: ${l.pct}% (${l.count} patterns)`).join('\n')}

### Category Focus
${profile.categories.slice(0, 5).map((c) => `- **${c.category}**: ${c.pct}% (${c.count} patterns)`).join('\n')}

### Frameworks
${profile.frameworks.slice(0, 5).map((f) => `- ${f.framework}: ${f.count} patterns`).join('\n')}
`,
        patterns: profile.categories.map((c) => c.category),
    };
    const patternsSection = {
        title: 'Key Patterns',
        content: `## Most Used Patterns

${profile.topPatterns.slice(0, 10).map((p, i) => `${i + 1}. **${p.description}** — Accept rate: ${(p.acceptRate * 100).toFixed(0)}%`).join('\n')}

### Common Transformations
${profile.patternSequences.slice(0, 10).map((s, i) => `${i + 1}. \`${s.from}\` → \`${s.to}\` (${s.count}x)`).join('\n')}
`,
        patterns: profile.topPatterns.map((p) => p.patternId),
    };
    const recommendationsSection = {
        title: 'Recommendations',
        content: `## Recommendations

Based on the project's pattern analysis:

1. **Adopt Best Practices**: The project strongly favors ${profile.primaryLanguage} with ${profile.averageConfidence >= 0.7 ? 'high' : 'moderate'} confidence patterns.
2. **Focus Areas**: ${profile.categories.slice(0, 3).map((c) => c.category).join(', ')} are the most active categories.
3. **Consistency**: ${profile.languages.length > 1 ? `Maintain consistency across ${profile.languages.length} detected languages.` : 'Single language project — keep conventions uniform.'}
4. **Pattern Growth**: ${profile.totalPatterns >= 50 ? 'Mature pattern library established.' : 'Growing pattern library — encourage team contributions.'}
`,
        patterns: [],
    };
    const onboardingSection = {
        title: 'Onboarding Guide',
        content: `## Onboarding Guide for New Contributors

### Quick Start
1. Install Fivo Cell daemon
2. The daemon will automatically detect patterns matching this project's style
3. Review suggested patterns before accepting

### Key Patterns to Learn
${topPatternsDesc || 'No patterns yet — start contributing!'}

### Convention Checklist
- [ ] Use ${profile.primaryLanguage} for new files
- [ ] Follow the project's detected category conventions
- [ ] Review accepted patterns to understand team preferences
`,
        patterns: profile.topPatterns.map((p) => p.patternId),
    };
    const playbook = {
        projectId,
        projectName: profile.name,
        generatedAt: Date.now(),
        overview,
        conventions: conventionsSection,
        patterns: patternsSection,
        recommendations: recommendationsSection,
        onboardingGuide: onboardingSection,
    };
    fs.writeFileSync(playbookPath(projectId), JSON.stringify(playbook, null, 2), 'utf-8');
    return playbook;
}
function getPlaybook(projectId) {
    try {
        const fp = playbookPath(projectId);
        if (!fs.existsSync(fp))
            return null;
        return JSON.parse(fs.readFileSync(fp, 'utf-8'));
    }
    catch {
        return null;
    }
}
function listPlaybooks() {
    ensureDir();
    try {
        return fs.readdirSync(PLAYBOOKS_DIR)
            .filter((f) => f.endsWith('.json'))
            .map((f) => f.replace('.json', ''));
    }
    catch {
        return [];
    }
}
function getPlaybooksDir() {
    return PLAYBOOKS_DIR;
}
//# sourceMappingURL=playbook-generator.js.map