"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StructureEngine = void 0;
const cell_store_1 = require("../walls/06-memory/stores/cell-store");
class StructureEngine {
    store;
    data;
    constructor(cellDir) {
        this.store = new cell_store_1.CellStore(cellDir);
        this.data = this.store.read('structure.json', 'personal', 'style') || {
            version: 1,
            updated: Date.now(),
            avgFileSize: 0,
            filesAnalyzed: 0,
            avgFunctionLength: 0,
            functionsAnalyzed: 0,
            nestingDepth: { average: 0, max: 0, deepFunctions: 0 },
            earlyReturns: { percentage: 0, total: 0, withEarlyReturn: 0 },
            guardClauses: { percentage: 0, total: 0 },
        };
    }
    analyze(code) {
        if (!code || code.length < 20)
            return { functionsFound: 0 };
        const lines = code.split('\n');
        const fileSize = lines.length;
        // File size
        const prevTotal = this.data.avgFileSize * this.data.filesAnalyzed;
        this.data.filesAnalyzed++;
        this.data.avgFileSize = Math.round((prevTotal + fileSize) / this.data.filesAnalyzed);
        // Functions
        const funcMatches = code.match(/(?:function\s+\w+|const\s+\w+\s*=\s*(?:async\s*)?\([^)]*\)\s*=>\s*\{|async\s+function\s+\w+)/g);
        if (!funcMatches)
            return { functionsFound: 0 };
        for (const func of funcMatches) {
            const funcBody = this.extractBody(code, code.indexOf(func));
            if (!funcBody)
                continue;
            const funcLines = funcBody.split('\n').length;
            const prevAvg = this.data.avgFunctionLength * this.data.functionsAnalyzed;
            this.data.functionsAnalyzed++;
            this.data.avgFunctionLength = Math.round((prevAvg + funcLines) / this.data.functionsAnalyzed);
            // Nesting depth
            const depth = this.calcDepth(funcBody);
            if (depth > this.data.nestingDepth.max)
                this.data.nestingDepth.max = depth;
            const prevDepth = this.data.nestingDepth.average * (this.data.functionsAnalyzed - 1);
            this.data.nestingDepth.average = Math.round((prevDepth + depth) / this.data.functionsAnalyzed);
            if (depth > 4)
                this.data.nestingDepth.deepFunctions++;
            // Early returns
            this.data.earlyReturns.total++;
            const bodyStart = funcBody.indexOf('{');
            const firstStmt = funcBody.slice(bodyStart + 1, bodyStart + 80).trim();
            if (/^if\b/.test(firstStmt) && /\breturn\b/.test(funcBody.slice(bodyStart, bodyStart + 200))) {
                this.data.earlyReturns.withEarlyReturn++;
            }
            this.data.earlyReturns.percentage = Math.round(this.data.earlyReturns.withEarlyReturn / this.data.earlyReturns.total * 100);
            // Guard clauses
            const guardCount = (funcBody.match(/^(?:\s*)if\b[^{]*\{[^}]*\breturn\b/gm) || []).length;
            this.data.guardClauses.total += guardCount;
            this.data.guardClauses.percentage = Math.round(this.data.guardClauses.total / this.data.functionsAnalyzed * 100);
        }
        this.data.updated = Date.now();
        this.store.write('structure.json', this.data, 'personal', 'style');
        return { functionsFound: funcMatches.length };
    }
    getSummary() {
        const lines = [];
        if (this.data.functionsAnalyzed === 0)
            return [];
        lines.push(`Avg file: ${this.data.avgFileSize} lines · Avg function: ${this.data.avgFunctionLength} lines`);
        lines.push(`Nesting: avg ${this.data.nestingDepth.average}, max ${this.data.nestingDepth.max}, deep: ${this.data.nestingDepth.deepFunctions}`);
        lines.push(`Early returns: ${this.data.earlyReturns.percentage}% · Guard clauses: ${this.data.guardClauses.percentage}%`);
        return lines;
    }
    extractBody(code, startIdx) {
        const braceStart = code.indexOf('{', startIdx);
        if (braceStart === -1)
            return null;
        let depth = 0;
        let braceEnd = -1;
        for (let i = braceStart; i < code.length; i++) {
            if (code[i] === '{')
                depth++;
            if (code[i] === '}') {
                depth--;
                if (depth === 0) {
                    braceEnd = i;
                    break;
                }
            }
        }
        if (braceEnd === -1)
            return null;
        return code.slice(braceStart, braceEnd + 1);
    }
    calcDepth(body) {
        let maxDepth = 0;
        let depth = 0;
        for (const ch of body) {
            if (ch === '{') {
                depth++;
                if (depth > maxDepth)
                    maxDepth = depth;
            }
            if (ch === '}')
                depth--;
        }
        return maxDepth;
    }
}
exports.StructureEngine = StructureEngine;
//# sourceMappingURL=structure-engine.js.map