"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.CellStore = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class CellStore {
    basePath;
    constructor(cellDir) {
        this.basePath = cellDir || path.join(process.cwd(), '.cell');
        this.ensure('personal', 'projects');
    }
    ensure(...segments) {
        const dir = path.join(this.basePath, ...segments);
        if (!fs.existsSync(dir))
            fs.mkdirSync(dir, { recursive: true });
    }
    resolve(...segments) {
        return path.join(this.basePath, ...segments);
    }
    read(filename, ...dirs) {
        try {
            const p = this.resolve(...dirs, filename);
            if (!fs.existsSync(p))
                return null;
            return JSON.parse(fs.readFileSync(p, 'utf-8'));
        }
        catch {
            return null;
        }
    }
    readRaw(filename) {
        const parts = filename.replace(/\\/g, '/').split('/');
        return this.read(parts.pop(), ...parts);
    }
    write(filename, data, ...dirs) {
        try {
            const p = this.resolve(...dirs, filename);
            this.ensure(...dirs);
            fs.writeFileSync(p, JSON.stringify(data, null, 2));
        }
        catch { }
    }
    exists(filename, ...dirs) {
        return fs.existsSync(this.resolve(...dirs, filename));
    }
    delete(filename, ...dirs) {
        try {
            fs.unlinkSync(this.resolve(...dirs, filename));
        }
        catch { }
    }
    list(dir) {
        try {
            return fs.readdirSync(this.resolve(dir));
        }
        catch {
            return [];
        }
    }
    get baseDir() { return this.basePath; }
    syncFromPatternStore(store) {
        let synced = 0;
        const patterns = store.getAllPatterns();
        const styleData = this.read('style.json', 'personal');
        if (!styleData)
            return { synced };
        for (const p of patterns) {
            const pref = p.to || p.description;
            if (!styleData.syntax.some(s => s.category === p.category && s.preference === pref)) {
                styleData.syntax.push({
                    category: p.category,
                    preference: pref,
                    confidence: p.confidence?.mean || 0.5,
                    signals: { positive: p.signals?.positive || 0, negative: p.signals?.negative || 0 },
                    firstSeen: p.lifecycle?.firstSeen || Date.now(),
                    lastSeen: p.lifecycle?.lastSeen || Date.now(),
                    language: p.meta?.language,
                });
                synced++;
            }
        }
        if (synced > 0) {
            styleData.updated = Date.now();
            this.write('style.json', styleData, 'personal');
        }
        return { synced };
    }
    migrateFromLegacy(legacyDir) {
        let migrated = 0;
        let skipped = 0;
        const legacyPath = path.join(legacyDir, 'cell.json');
        if (!fs.existsSync(legacyPath))
            return { migrated, skipped };
        try {
            const legacy = JSON.parse(fs.readFileSync(legacyPath, 'utf-8'));
            const patterns = legacy.patterns || [];
            if (!this.exists('style.json', 'personal')) {
                const styleData = {
                    version: 1,
                    updated: Date.now(),
                    syntax: [],
                    naming: [],
                    structure: { avgFileSize: 0, avgFunctionLength: 0, earlyReturns: 0, nestingDepth: 2 },
                };
                this.write('style.json', styleData, 'personal');
                migrated++;
            }
            // Migrate patterns to style
            const existing = this.read('style.json', 'personal');
            if (existing && patterns.length > 0) {
                for (const p of patterns) {
                    if (!existing.syntax.some(s => s.category === p.category && s.preference === p.to)) {
                        existing.syntax.push({
                            category: p.category,
                            preference: p.to || p.description,
                            confidence: p.confidence?.mean || 0.5,
                            signals: p.signals || { positive: 0, negative: 0 },
                            firstSeen: p.lifecycle?.firstSeen || Date.now(),
                            lastSeen: p.lifecycle?.lastSeen || Date.now(),
                        });
                        migrated++;
                    }
                    else {
                        skipped++;
                    }
                }
                existing.updated = Date.now();
                this.write('style.json', existing, 'personal');
            }
        }
        catch {
            skipped = 0;
        }
        return { migrated, skipped };
    }
}
exports.CellStore = CellStore;
//# sourceMappingURL=cell-store.js.map