"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.CommunityPrior = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class CommunityPrior {
    priorPath;
    patterns = new Map();
    constructor(cellDir) {
        this.priorPath = path.join(cellDir, 'community', 'prior.json');
        this.ensureDirectory(path.dirname(this.priorPath));
        this.load();
    }
    generateSyntheticSeed() {
        if (this.patterns.size > 0) {
            return this.getPatterns();
        }
        const syntheticPatterns = [
            this.makePattern('seed_var_to_const', 'variable_declaration', 'Prefers const over let for immutable bindings', 'var', 'const', 0.65),
            this.makePattern('seed_func_to_arrow', 'function_style', 'Prefers arrow functions for callbacks', 'function', 'arrow', 0.62),
            this.makePattern('seed_double_to_single_quotes', 'quote_style', 'Prefers single quotes for strings', 'double', 'single', 0.58),
            this.makePattern('seed_loose_to_strict_equality', 'equality', 'Prefers strict equality (===) over loose (==)', '==', '===', 0.70),
            this.makePattern('seed_default_to_named_export', 'export_style', 'Prefers named exports over default exports', 'default', 'named', 0.55),
            this.makePattern('seed_require_to_import', 'module_system', 'Prefers ES module import over require', 'require', 'import', 0.68),
            this.makePattern('seed_then_to_async_await', 'promise_style', 'Prefers async/await over .then() chains', '.then()', 'await', 0.63),
            this.makePattern('seed_untyped_to_typed', 'type_annotation', 'Adds TypeScript type annotations to function parameters', 'untyped', 'typed', 0.60),
            this.makePattern('seed_no_try_catch', 'error_handling', 'Wraps async operations in try/catch blocks', 'no_try_catch', 'try_catch', 0.55),
            this.makePattern('seed_null_check', 'null_safety', 'Adds null checks before property access', 'no_null_check', 'null_check', 0.58),
        ];
        for (const pattern of syntheticPatterns) {
            this.patterns.set(pattern.patternId, {
                pattern,
                sourceCount: 0,
                isSynthetic: true,
            });
        }
        this.save();
        return syntheticPatterns;
    }
    getPatterns(minConfidence = 0) {
        return Array.from(this.patterns.values())
            .filter((cp) => cp.pattern.confidence.mean >= minConfidence)
            .map((cp) => cp.pattern);
    }
    getSyntheticPatterns() {
        return Array.from(this.patterns.values())
            .filter((cp) => cp.isSynthetic)
            .map((cp) => cp.pattern);
    }
    getLivePatterns() {
        return Array.from(this.patterns.values())
            .filter((cp) => !cp.isSynthetic)
            .map((cp) => cp.pattern);
    }
    addLivePattern(pattern, sourceCount = 1) {
        this.patterns.set(pattern.patternId, {
            pattern,
            sourceCount,
            isSynthetic: false,
        });
        this.save();
    }
    replaceSyntheticWithLive(syntheticId, livePattern) {
        const existing = this.patterns.get(syntheticId);
        if (!existing || !existing.isSynthetic)
            return false;
        this.patterns.set(syntheticId, {
            pattern: { ...livePattern, patternId: syntheticId },
            sourceCount: 1,
            isSynthetic: false,
        });
        this.save();
        return true;
    }
    getDisplayLabel() {
        const liveCount = this.getLivePatterns().length;
        const syntheticCount = this.getSyntheticPatterns().length;
        if (liveCount > 0 && syntheticCount > 0) {
            return `Community patterns (${liveCount} live + ${syntheticCount} synthetic, improving with real data)`;
        }
        if (liveCount > 0) {
            return `Community patterns (learned from ${liveCount} developers)`;
        }
        return 'Community patterns (synthetic seed, improving with real data)';
    }
    getCommunityPattern(id) {
        return this.patterns.get(id);
    }
    getPatternCount() {
        return this.patterns.size;
    }
    save() {
        const data = Array.from(this.patterns.values());
        fs.writeFileSync(this.priorPath, JSON.stringify(data, null, 2), 'utf-8');
    }
    clear() {
        this.patterns.clear();
        this.save();
    }
    load() {
        if (fs.existsSync(this.priorPath)) {
            try {
                const data = JSON.parse(fs.readFileSync(this.priorPath, 'utf-8'));
                for (const cp of data) {
                    this.patterns.set(cp.pattern.patternId, cp);
                }
            }
            catch {
                this.patterns.clear();
            }
        }
    }
    makePattern(id, category, description, from, to, confidence) {
        return {
            patternId: id,
            category,
            description,
            from,
            to,
            conditions: [],
            confidence: {
                distribution: 'beta',
                alpha: Math.round(confidence * 15),
                beta: Math.round((1 - confidence) * 15),
                mean: confidence,
                ci95: [Math.max(0, confidence - 0.1), Math.min(1, confidence + 0.1)],
            },
            signals: {
                positive: 10,
                negative: 5,
                total: 15,
                lastSignal: Date.now(),
            },
            attribution: {
                primaryCondition: 'synthetic_seed',
                conditionConfidence: 0,
                sourceFiles: [],
                note: 'Synthetic seed pattern — not from real user data',
            },
            scope: 'global',
            survivedDays: 0,
            meta: { language: 'unknown', subcategory: 'general', complexity: 'low', risk: 'medium', source: 'import' },
            lifecycle: { firstSeen: Date.now(), lastSeen: Date.now(), version: 1, history: [] },
            quality: { score: 50, reuseRate: 0, successRate: 0, failureRate: 0, acceptanceRate: 0, daysSinceLastSignal: 0, age: 0 },
            relationships: { related: [], conflicting: [], complementary: [], dependencies: [] },
            ranking: { score: 0, rank: 0, factors: { confidence: 0, quality: 0, usage: 0, recency: 0, acceptance: 0 } },
        };
    }
    ensureDirectory(dir) {
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
    }
}
exports.CommunityPrior = CommunityPrior;
//# sourceMappingURL=community-prior.js.map