"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 });
const session_memory_1 = require("../walls/01-context/sessions/session-memory");
const database_1 = require("../walls/06-memory/database/database");
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
describe('@cell MCP tools (Unit 2.7)', () => {
    let mem;
    let originalHome;
    let tmpHome;
    beforeAll(() => {
        tmpHome = path.join(os.tmpdir(), 'fivo-cell-mcp-test-' + Date.now());
        fs.mkdirSync(tmpHome, { recursive: true });
        originalHome = process.env.USERPROFILE;
        process.env.USERPROFILE = tmpHome;
        try {
            (0, database_1.closeDb)();
        }
        catch { /* ignore */ }
        mem = new session_memory_1.SessionMemory();
    });
    afterAll(() => {
        process.env.USERPROFILE = originalHome;
        try {
            (0, database_1.closeDb)();
        }
        catch { /* ignore */ }
        try {
            fs.rmSync(tmpHome, { recursive: true, force: true });
        }
        catch { /* ignore */ }
    });
    beforeEach(() => {
        try {
            (0, database_1.closeDb)();
        }
        catch { /* ignore */ }
        mem = new session_memory_1.SessionMemory();
        try {
            const db = (0, database_1.getDb)();
            db.exec('DELETE FROM sessions; DELETE FROM session_approaches; DELETE FROM session_files; DELETE FROM session_questions;');
        }
        catch { /* ignore */ }
    });
    it('cell_session_start creates a new session and returns ID', () => {
        const project = 'fivo-cell-test-1-start';
        const sId = mem.startSession('claude-code', project);
        expect(sId).toBeGreaterThan(0);
        const recent = mem.getRecentSessions(1);
        expect(recent[0].id).toBe(sId);
        expect(recent[0].toolName).toBe('claude-code');
        expect(recent[0].project).toBe(project);
    });
    it('cell_session_status returns active session info', () => {
        const project = 'fivo-cell-test-2-status';
        const sId = mem.startSession('cursor', project);
        mem.recordFileTouch({ sessionId: sId, project, filePath: 'src/foo.ts' });
        mem.recordFileTouch({ sessionId: sId, project, filePath: 'src/bar.ts' });
        mem.recordApproach({ sessionId: sId, project, approach: 'chokidar', status: 'failed' });
        mem.recordQuestion({ sessionId: sId, project, question: 'How to detect tool switch?', priority: 'high' });
        const db = (0, database_1.getDb)();
        const sess = db.prepare('SELECT * FROM sessions WHERE id = ?').get(sId);
        expect(sess).toBeDefined();
        expect(sess.tool_name).toBe('cursor');
        expect(sess.end_time).toBeNull();
        const files = mem.getSessionFiles(sId);
        expect(files.length).toBe(2);
        const approaches = mem.getSessionApproaches(sId);
        expect(approaches.length).toBe(1);
        const questions = mem.getOpenQuestions(project);
        expect(questions.length).toBe(1);
        expect(questions[0].question).toContain('tool switch');
    });
    it('cell_session_recent returns last N sessions for project', async () => {
        const project = 'fivo-cell-test-3-recent';
        const s1 = mem.startSession('claude-code', project);
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: 'first' });
        await new Promise(r => setTimeout(r, 5));
        const s2 = mem.startSession('cursor', project);
        mem.endSession(s2, { filesTouched: [], keyDecisions: [], contextSnapshot: 'second' });
        await new Promise(r => setTimeout(r, 5));
        const s3 = mem.startSession('windsurf', project);
        mem.endSession(s3, { filesTouched: [], keyDecisions: [], contextSnapshot: 'third' });
        const recent = mem.getRecentSessions(10).filter(s => s.project === project);
        expect(recent.length).toBe(3);
        expect(recent[0].toolName).toBe('windsurf');
        expect(recent[1].toolName).toBe('cursor');
        expect(recent[2].toolName).toBe('claude-code');
    });
    it('cell_session_recommendations: detect unused approaches (likely good suggestions)', () => {
        const project = 'fivo-cell-test-4-avoid';
        const s1 = mem.startSession('claude-code', project);
        mem.recordApproach({ sessionId: s1, project, approach: 'use chokidar', status: 'failed' });
        mem.recordApproach({ sessionId: s1, project, approach: 'use JSON files', status: 'partial' });
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
        const recent = mem.getRecentApproaches(project, 10);
        expect(recent.length).toBe(2);
        const failed = recent.find(a => a.approach === 'use chokidar');
        expect(failed?.status).toBe('failed');
    });
    it('cell_session_recommendations: surfaces open questions as guidance', () => {
        const project = 'fivo-cell-test-5-q';
        const s1 = mem.startSession('claude-code', project);
        mem.recordQuestion({ sessionId: s1, project, question: 'Should we use TypeScript strict mode?', priority: 'high' });
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
        const open = mem.getOpenQuestions(project);
        expect(open.length).toBeGreaterThan(0);
        const q = open.find(x => x.question.includes('TypeScript'));
        expect(q?.priority).toBe('high');
    });
    it('cell_session_aggregate_stats: getSessionStats returns tool/project breakdown', () => {
        const projectA = 'fivo-cell-test-6a-stats';
        const projectB = 'fivo-cell-test-6b-stats';
        const s1 = mem.startSession('claude-code', projectA);
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: 'a1' });
        const s2 = mem.startSession('cursor', projectA);
        mem.endSession(s2, { filesTouched: [], keyDecisions: [], contextSnapshot: 'a2' });
        const s3 = mem.startSession('claude-code', projectB);
        mem.endSession(s3, { filesTouched: [], keyDecisions: [], contextSnapshot: 'b1' });
        const stats = mem.getSessionStats();
        expect(stats.totalSessions).toBeGreaterThanOrEqual(3);
        const byTool = stats.byTool;
        const claudeCount = byTool.find(t => t.tool_name === 'claude-code')?.count || 0;
        const cursorCount = byTool.find(t => t.tool_name === 'cursor')?.count || 0;
        expect(claudeCount).toBeGreaterThanOrEqual(2);
        expect(cursorCount).toBeGreaterThanOrEqual(1);
    });
    it('cell_session_recent includes cross-project sessions when no project filter', () => {
        const projectA = 'fivo-cell-test-7a-cross';
        const projectB = 'fivo-cell-test-7b-cross';
        const s1 = mem.startSession('claude-code', projectA);
        mem.endSession(s1, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
        const s2 = mem.startSession('claude-code', projectB);
        mem.endSession(s2, { filesTouched: [], keyDecisions: [], contextSnapshot: '' });
        const recent = mem.getRecentSessions(20);
        const foundA = recent.find(s => s.project === projectA);
        const foundB = recent.find(s => s.project === projectB);
        expect(foundA).toBeDefined();
        expect(foundB).toBeDefined();
    });
});
//# sourceMappingURL=mcp-cell-tools.test.js.map