"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.loadStylePatterns = loadStylePatterns;
exports.detectFormattingFromCodebase = detectFormattingFromCodebase;
exports.buildStyleSummary = buildStyleSummary;
exports.generateAgentMd = generateAgentMd;
exports.generateCursorRules = generateCursorRules;
exports.generateClaudeMd = generateClaudeMd;
exports.generateCopilotInstructions = generateCopilotInstructions;
exports.generateAntigravityPrompt = generateAntigravityPrompt;
exports.generatePrettierRc = generatePrettierRc;
exports.generateEslintRules = generateEslintRules;
exports.writeStyleFiles = writeStyleFiles;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
function loadStylePatterns() {
    const paths = [
        path.join(os.homedir(), '.fivo', 'cell', 'onboarding.json'),
        path.join(os.homedir(), '.fivo', 'cell', 'cell.json'),
    ];
    for (const p of paths) {
        if (!fs.existsSync(p))
            continue;
        try {
            const data = JSON.parse(fs.readFileSync(p, 'utf-8'));
            if (data.patterns && Array.isArray(data.patterns)) {
                return data.patterns.filter((x) => x.category !== 'file-signature');
            }
        }
        catch { }
    }
    return [];
}
function detectFormattingFromCodebase(rootDir) {
    const fmt = {
        semicolons: true,
        quotes: 'single',
        indentSize: 2,
        indentStyle: 'space',
        trailingComma: 'es5',
        lineWidth: 100,
    };
    let semiCount = 0;
    let singleQuoteCount = 0;
    let doubleQuoteCount = 0;
    let totalStatements = 0;
    let totalLines = 0;
    function walk(dir, depth = 0) {
        if (depth > 5)
            return;
        let entries;
        try {
            entries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const e of entries) {
            if (e.name === 'node_modules' || e.name.startsWith('.') || e.name === 'dist' || e.name === 'build')
                continue;
            const full = path.join(dir, e.name);
            if (e.isDirectory())
                walk(full, depth + 1);
            else if (e.isFile() && /\.(ts|tsx|js|jsx)$/.test(e.name)) {
                try {
                    const content = fs.readFileSync(full, 'utf-8');
                    const lines = content.split('\n').slice(0, 200);
                    totalLines += lines.length;
                    for (const line of lines) {
                        const trimmed = line.trim();
                        if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('*'))
                            continue;
                        if (trimmed.endsWith(';') && !trimmed.endsWith('*/') && !trimmed.startsWith('//'))
                            semiCount++;
                        if (/'[^']*'/.test(trimmed))
                            singleQuoteCount++;
                        if (/"[^"]*"/.test(trimmed))
                            doubleQuoteCount++;
                        totalStatements++;
                    }
                }
                catch { }
            }
        }
    }
    walk(rootDir);
    if (totalStatements > 0) {
        fmt.semicolons = semiCount / totalStatements > 0.5;
        fmt.quotes = singleQuoteCount > doubleQuoteCount * 1.2 ? 'single' :
            doubleQuoteCount > singleQuoteCount * 1.2 ? 'double' : 'mixed';
    }
    const prettierPath = path.join(rootDir, '.prettierrc');
    if (fs.existsSync(prettierPath)) {
        try {
            const p = JSON.parse(fs.readFileSync(prettierPath, 'utf-8'));
            if (p.semi !== undefined)
                fmt.semicolons = p.semi;
            if (p.singleQuote !== undefined)
                fmt.quotes = p.singleQuote ? 'single' : 'double';
            if (p.tabWidth)
                fmt.indentSize = p.tabWidth;
            if (p.useTabs !== undefined)
                fmt.indentStyle = p.useTabs ? 'tab' : 'space';
            if (p.trailingComma)
                fmt.trailingComma = p.trailingComma;
            if (p.printWidth)
                fmt.lineWidth = p.printWidth;
        }
        catch { }
    }
    return fmt;
}
function buildStyleSummary(rootDir) {
    const patterns = loadStylePatterns();
    const sorted = [...patterns].sort((a, b) => (b.evidence * b.trustScore) - (a.evidence * a.trustScore));
    const top = sorted.slice(0, 15);
    const byCategory = {};
    for (const p of sorted) {
        if (!byCategory[p.category])
            byCategory[p.category] = [];
        byCategory[p.category].push(p);
    }
    const detectedRoot = rootDir || os.homedir();
    const formatting = detectFormattingFromCodebase(detectedRoot);
    const langs = new Set();
    const frameworks = new Set();
    for (const p of patterns) {
        if (p.language)
            langs.add(p.language);
    }
    return {
        topPatterns: top,
        byCategory,
        formatting,
        language: Array.from(langs).join(', ') || 'TypeScript',
        framework: Array.from(frameworks),
        generatedAt: new Date().toISOString(),
    };
}
function formatPatternLine(p) {
    return `- ${p.description} (trustScore: ${Math.round(p.trustScore * 100)}%, evidence: ${p.evidence} times)`;
}
function generateAgentMd(s) {
    const lines = [];
    lines.push('# AGENT STYLE GUIDE — Generated by FIVO Cell');
    lines.push('');
    lines.push(`> Auto-generated: ${s.generatedAt}`);
    lines.push('> This file teaches AI coding assistants (Cursor, Claude, Copilot, Antigravity) your coding style.');
    lines.push('> Edit it as needed. Run `cell pull` to regenerate.');
    lines.push('');
    lines.push('## 🎯 Quick style summary');
    lines.push('');
    lines.push(`- **Language**: ${s.language}`);
    lines.push(`- **Semicolons**: ${s.formatting.semicolons ? 'YES — always use `;`' : 'NO — never use `;`'}`);
    lines.push(`- **Quotes**: ${s.formatting.quotes === 'single' ? 'single quotes `\'...\'' : s.formatting.quotes === 'double' ? 'double quotes `"..."`' : 'mixed (prefer single)'}`);
    lines.push(`- **Indent**: ${s.formatting.indentSize} ${s.formatting.indentStyle}s`);
    lines.push(`- **Line width**: ${s.formatting.lineWidth} chars max`);
    lines.push(`- **Trailing comma**: ${s.formatting.trailingComma}`);
    lines.push('');
    lines.push('## 📐 Top coding patterns (these are non-negotiable)');
    lines.push('');
    for (const p of s.topPatterns) {
        lines.push(formatPatternLine(p));
    }
    lines.push('');
    lines.push('## 🏷️ Patterns by category');
    lines.push('');
    for (const cat of Object.keys(s.byCategory).sort()) {
        lines.push(`### ${cat}`);
        lines.push('');
        for (const p of s.byCategory[cat].slice(0, 5)) {
            lines.push(formatPatternLine(p));
        }
        lines.push('');
    }
    lines.push('## 🚫 Things to AVOID');
    lines.push('');
    lines.push('- Mixing style (always follow patterns above)');
    lines.push('- Adding `any` type (use `unknown` and narrow)');
    lines.push('- Default exports (use named exports)');
    lines.push('- Class declarations for everything (prefer functions)');
    lines.push('- `var` (always use `const` or `let`)');
    lines.push('');
    return lines.join('\n');
}
function generateCursorRules(s) {
    const lines = [];
    lines.push('# Cursor Rules — Auto-generated by FIVO Cell');
    lines.push('');
    lines.push('When generating code in this project:');
    lines.push('');
    lines.push('## Formatting (MANDATORY)');
    lines.push(`- ${s.formatting.semicolons ? 'Use semicolons' : 'NO semicolons'}`);
    lines.push(`- ${s.formatting.quotes === 'single' ? 'Single quotes' : s.formatting.quotes === 'double' ? 'Double quotes' : 'Prefer single quotes'} for strings`);
    lines.push(`- Indent: ${s.formatting.indentSize} ${s.formatting.indentStyle}s`);
    lines.push(`- Line width: ${s.formatting.lineWidth} chars`);
    lines.push(`- Trailing comma: ${s.formatting.trailingComma}`);
    lines.push('');
    lines.push('## Style patterns (apply these ALWAYS)');
    lines.push('');
    for (const p of s.topPatterns.slice(0, 12)) {
        lines.push(`- ${p.description}`);
    }
    lines.push('');
    lines.push('## Things to avoid');
    lines.push('');
    lines.push('- Using `any` type — use `unknown` instead');
    lines.push('- Default exports — use named exports');
    lines.push('- `var` keyword — use `const` or `let`');
    lines.push('');
    return lines.join('\n');
}
function generateClaudeMd(s) {
    const lines = [];
    lines.push('# Project Coding Style — FIVO Cell');
    lines.push('');
    lines.push(`Auto-generated from user's learned style. Generated: ${s.generatedAt.split('T')[0]}.`);
    lines.push('');
    lines.push('## When you write code, follow these rules:');
    lines.push('');
    lines.push('### Formatting');
    lines.push(`- ${s.formatting.semicolons ? 'Always use semicolons' : 'Do not use semicolons'}`);
    lines.push(`- ${s.formatting.quotes === 'single' ? 'Use single quotes' : s.formatting.quotes === 'double' ? 'Use double quotes' : 'Prefer single quotes'} for strings`);
    lines.push(`- Indent with ${s.formatting.indentSize} ${s.formatting.indentStyle}s`);
    lines.push(`- Keep lines under ${s.formatting.lineWidth} characters`);
    lines.push('');
    lines.push('### Style rules (apply these to every line of code)');
    lines.push('');
    for (const p of s.topPatterns.slice(0, 10)) {
        lines.push(`- ${p.description}`);
    }
    lines.push('');
    lines.push('### Things to NEVER do');
    lines.push('');
    lines.push('- Use `any` type (use `unknown` and narrow)');
    lines.push('- Use default exports (use named exports)');
    lines.push('- Use `var` (use `const` or `let`)');
    lines.push('- Skip try/catch on risky operations');
    lines.push('');
    return lines.join('\n');
}
function generateCopilotInstructions(s) {
    const lines = [];
    lines.push('# GitHub Copilot Instructions');
    lines.push('');
    lines.push('Auto-generated by FIVO Cell. When suggesting code, follow these patterns:');
    lines.push('');
    lines.push('## Code formatting');
    lines.push(`- Semicolons: ${s.formatting.semicolons ? 'required' : 'forbidden'}`);
    lines.push(`- Quotes: ${s.formatting.quotes}`);
    lines.push(`- Indent: ${s.formatting.indentSize} ${s.formatting.indentStyle}s`);
    lines.push('');
    lines.push('## Style patterns');
    lines.push('');
    for (const p of s.topPatterns.slice(0, 8)) {
        lines.push(`- ${p.description}`);
    }
    lines.push('');
    return lines.join('\n');
}
function generateAntigravityPrompt(s) {
    const lines = [];
    lines.push('# Antigravity / Generic AI Agent Rules');
    lines.push('');
    lines.push('You are an AI coding assistant. Follow these style rules:');
    lines.push('');
    lines.push('## Formatting');
    lines.push(`- ${s.formatting.semicolons ? 'Always use semicolons' : 'No semicolons'}`);
    lines.push(`- ${s.formatting.quotes === 'single' ? 'Single quotes' : s.formatting.quotes === 'double' ? 'Double quotes' : 'Prefer single quotes'} for strings`);
    lines.push(`- Indent: ${s.formatting.indentSize} ${s.formatting.indentStyle}s`);
    lines.push(`- Line width: ${s.formatting.lineWidth} chars`);
    lines.push('');
    lines.push('## Required style patterns');
    lines.push('');
    for (const p of s.topPatterns.slice(0, 12)) {
        lines.push(`- ${p.description}`);
    }
    lines.push('');
    lines.push('## Hard rules');
    lines.push('');
    lines.push('- Use `unknown` not `any`');
    lines.push('- Use named exports not default');
    lines.push('- Use `const` or `let` not `var`');
    lines.push('- Wrap risky code in try/catch');
    lines.push('- Use parameterized queries for SQL (security)');
    lines.push('');
    return lines.join('\n');
}
function generatePrettierRc(s) {
    return JSON.stringify({
        semi: s.formatting.semicolons,
        singleQuote: s.formatting.quotes === 'single',
        tabWidth: s.formatting.indentSize,
        useTabs: s.formatting.indentStyle === 'tab',
        trailingComma: s.formatting.trailingComma,
        printWidth: s.formatting.lineWidth,
    }, null, 2) + '\n';
}
function generateEslintRules(s) {
    const rules = {
        semi: s.formatting.semicolons ? ['error', 'always'] : ['error', 'never'],
        quotes: s.formatting.quotes === 'single' ? ['error', 'single'] :
            s.formatting.quotes === 'double' ? ['error', 'double'] :
                ['warn', 'single', { avoidEscape: true }],
        'no-var': 'error',
        'prefer-const': 'error',
        '@typescript-eslint/no-explicit-any': 'error',
    };
    if (s.topPatterns.some(p => p.description.includes('arrow functions'))) {
        rules['prefer-arrow-callback'] = 'error';
    }
    if (s.topPatterns.some(p => p.description.includes('const over let'))) {
        rules['prefer-const'] = 'error';
    }
    return JSON.stringify({ rules }, null, 2) + '\n';
}
function writeStyleFiles(targetDir, summary, opts = {}) {
    const tools = opts.tools || ['agent', 'cursor', 'claude', 'copilot', 'antigravity', 'prettier', 'eslint'];
    const written = [];
    const skipped = [];
    const files = [];
    if (tools.includes('agent'))
        files.push({ path: 'AGENT.md', content: generateAgentMd(summary), tool: 'Generic AI Agent' });
    if (tools.includes('cursor'))
        files.push({ path: '.cursorrules', content: generateCursorRules(summary), tool: 'Cursor' });
    if (tools.includes('claude'))
        files.push({ path: 'CLAUDE.md', content: generateClaudeMd(summary), tool: 'Claude Code' });
    if (tools.includes('copilot')) {
        const dir = path.join(targetDir, '.github');
        if (!fs.existsSync(dir))
            fs.mkdirSync(dir, { recursive: true });
        files.push({ path: path.join('.github', 'copilot-instructions.md'), content: generateCopilotInstructions(summary), tool: 'GitHub Copilot' });
    }
    if (tools.includes('antigravity'))
        files.push({ path: '.antigravity-rules.md', content: generateAntigravityPrompt(summary), tool: 'Antigravity / Generic' });
    if (tools.includes('prettier'))
        files.push({ path: '.prettierrc', content: generatePrettierRc(summary), tool: 'Prettier' });
    if (tools.includes('eslint'))
        files.push({ path: '.eslintrc-style.json', content: generateEslintRules(summary), tool: 'ESLint' });
    for (const f of files) {
        const full = path.join(targetDir, f.path);
        if (fs.existsSync(full) && !opts.force) {
            skipped.push(f.path);
            continue;
        }
        fs.writeFileSync(full, f.content, 'utf-8');
        written.push(f.path);
    }
    return { written, skipped };
}
//# sourceMappingURL=style-pull.js.map