"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.SolutionIndex = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class SolutionIndex {
    indexPath;
    solutions = new Map();
    minProjects;
    minSolutionsPerProject;
    constructor(cellDir) {
        this.indexPath = path.join(cellDir, 'solutions');
        this.minProjects = 2;
        this.minSolutionsPerProject = 5;
        this.ensureDirectory(this.indexPath);
        this.load();
    }
    addSolution(title, description, stack, projectId, tags, codeSnippet) {
        const solution = {
            id: `sol_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`,
            title,
            description,
            stack,
            projectId,
            timestamp: new Date().toISOString(),
            tags,
            codeSnippet,
        };
        this.solutions.set(solution.id, solution);
        this.save();
        return solution;
    }
    search(query) {
        const queryLower = query.toLowerCase();
        const results = [];
        for (const solution of this.solutions.values()) {
            let score = 0;
            if (solution.title.toLowerCase().includes(queryLower))
                score += 3;
            if (solution.description.toLowerCase().includes(queryLower))
                score += 2;
            if (solution.tags.some((t) => t.toLowerCase().includes(queryLower)))
                score += 2;
            if (solution.stack.some((s) => s.toLowerCase().includes(queryLower)))
                score += 1;
            if (solution.codeSnippet.toLowerCase().includes(queryLower))
                score += 1;
            if (score > 0) {
                results.push({ solution, score });
            }
        }
        return results
            .sort((a, b) => b.score - a.score)
            .slice(0, 10)
            .map((r) => r.solution);
    }
    findSimilar(description, stack) {
        const words = description.toLowerCase().split(/\s+/);
        const results = [];
        for (const solution of this.solutions.values()) {
            let score = 0;
            const solWords = solution.description.toLowerCase().split(/\s+/);
            for (const word of words) {
                if (solWords.includes(word))
                    score += 1;
            }
            const commonStack = solution.stack.filter((s) => stack.includes(s));
            score += commonStack.length * 2;
            if (score > 0) {
                results.push({ solution, score });
            }
        }
        return results
            .sort((a, b) => b.score - a.score)
            .slice(0, 5)
            .map((r) => r.solution);
    }
    isColdStart() {
        const projects = new Set();
        for (const solution of this.solutions.values()) {
            projects.add(solution.projectId);
        }
        if (projects.size < this.minProjects)
            return true;
        for (const projectId of projects) {
            const count = Array.from(this.solutions.values()).filter((s) => s.projectId === projectId).length;
            if (count < this.minSolutionsPerProject)
                return true;
        }
        return false;
    }
    getColdStartMessage() {
        return `Solution index is warming up. Need ≥${this.minProjects} projects with ≥${this.minSolutionsPerProject} solutions each. Current: ${this.getStats().projects} projects, ${this.getStats().totalSolutions} solutions.`;
    }
    getStats() {
        const projects = new Set();
        const tagCounts = new Map();
        for (const solution of this.solutions.values()) {
            projects.add(solution.projectId);
            for (const tag of solution.tags) {
                tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
            }
        }
        const topTags = Array.from(tagCounts.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, 5)
            .map(([tag]) => tag);
        return { projects: projects.size, totalSolutions: this.solutions.size, topTags };
    }
    getAllSolutions() {
        return Array.from(this.solutions.values());
    }
    clear() {
        this.solutions.clear();
        this.save();
    }
    save() {
        const data = Array.from(this.solutions.values());
        fs.writeFileSync(path.join(this.indexPath, 'index.json'), JSON.stringify(data, null, 2), 'utf-8');
    }
    load() {
        const filePath = path.join(this.indexPath, 'index.json');
        if (fs.existsSync(filePath)) {
            try {
                const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
                for (const solution of data) {
                    this.solutions.set(solution.id, solution);
                }
            }
            catch {
                this.solutions.clear();
            }
        }
    }
    ensureDirectory(dir) {
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
    }
}
exports.SolutionIndex = SolutionIndex;
//# sourceMappingURL=solution-index.js.map