"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const prompt_builder_1 = require("../walls/01-context/context/prompt-builder");
const mockDb = {
    prepare: jest.fn(),
};
jest.mock('../walls/06-memory/database/database', () => ({
    getDb: () => mockDb,
}));
function fakeStmt(rows) {
    return {
        all: (..._args) => rows,
        get: (..._args) => rows[0] || undefined,
    };
}
describe('@cell live_event fallback (regression for v4.1.8 UX bug)', () => {
    function setupMocks(opts = {}) {
        const profileTs = opts.profileScannedAt || new Date().toISOString();
        mockDb.prepare.mockReset();
        mockDb.prepare.mockImplementation((sql) => {
            const s = sql.trim().toUpperCase();
            if (s.startsWith('SELECT * FROM DEVELOPER_PROFILES')) {
                return fakeStmt([{ id: 1, project: 'fivo-cell', files_scanned: 100, total_lines: 5000, scanned_at: profileTs }]);
            }
            if (s.startsWith('SELECT PATTERN_TYPE, PATTERN_VALUE, CATEGORY, COUNT, TRUST_SCORE FROM CODE_PATTERNS')) {
                if (s.includes("CATEGORY = 'BLIND_SPOTS'"))
                    return fakeStmt([]);
                return fakeStmt([{ pattern_type: 'naming', pattern_value: 'camelCase', category: 'naming', count: 10, trust_score: 90 }]);
            }
            if (s.startsWith('SELECT * FROM SCANS')) {
                return fakeStmt([{ id: 1, project: 'fivo-cell', started_at: new Date().toISOString(), completed_at: new Date().toISOString(), files_scanned: 100 }]);
            }
            if (s.startsWith('SELECT * FROM ERROR_LOG'))
                return fakeStmt([]);
            if (s.startsWith('SELECT PATTERN_VALUE FROM CODE_PATTERNS'))
                return fakeStmt([]);
            if (s.startsWith('SELECT * FROM SESSIONS')) {
                return fakeStmt(opts.sessionRows || []);
            }
            if (s.startsWith('SELECT * FROM LIVE_EVENTS')) {
                return opts.liveEventRows ? fakeStmt(opts.liveEventRows) : fakeStmt([]);
            }
            if (s.includes('SESSION_APPROACHES') && s.includes('GROUP BY'))
                return fakeStmt([]);
            if (s.startsWith('SELECT FILE_PATH') && s.includes('SESSION_FILES'))
                return fakeStmt([]);
            if (s.startsWith('SELECT * FROM SESSION_QUESTIONS'))
                return fakeStmt([]);
            return fakeStmt([]);
        });
    }
    it('sets lastLiveFile when no session exists but live_events has rows', () => {
        const eventTs = new Date(Date.now() - 60_000).toISOString();
        setupMocks({
            sessionRows: [],
            liveEventRows: [{ id: 1217, project: 'fivo-cell', event_type: 'file_save', file_path: 'src/components/layout/AppLayout.tsx', created_at: eventTs }],
        });
        const ctx = (0, prompt_builder_1.buildContext)('fivo-cell', 'claude-code');
        expect(ctx.lastSession).toBeUndefined();
        expect(ctx.lastLiveFile).toBeDefined();
        expect(ctx.lastLiveFile?.filePath).toBe('src/components/layout/AppLayout.tsx');
        expect(ctx.lastLiveFile?.eventType).toBe('file_save');
    });
    it('@cell block shows "Live: saved <path>" when only live_event is present (regression for empty Last Session)', () => {
        const eventTs = new Date(Date.now() - 30_000).toISOString();
        setupMocks({
            sessionRows: [],
            liveEventRows: [{ id: 50, project: 'fivo-cell', event_type: 'file_save', file_path: 'src/foo.ts', created_at: eventTs }],
        });
        const ctx = (0, prompt_builder_1.buildContext)('fivo-cell', 'claude-code');
        const out = (0, prompt_builder_1.formatContextForTool)(ctx, 'claude-code');
        expect(out).toContain('Live: saved src/foo.ts');
        expect(out).not.toContain('(no session yet — first run)');
        expect(out).toContain('cell session start');
    });
    it('@cell block shows "Live: created <path>" for file_create events', () => {
        const eventTs = new Date().toISOString();
        setupMocks({
            sessionRows: [],
            liveEventRows: [{ id: 51, project: 'fivo-cell', event_type: 'file_create', file_path: 'src/new.ts', created_at: eventTs }],
        });
        const ctx = (0, prompt_builder_1.buildContext)('fivo-cell', 'claude-code');
        const out = (0, prompt_builder_1.formatContextForTool)(ctx, 'claude-code');
        expect(out).toContain('Live: created src/new.ts');
    });
    it('@cell block shows "Live: deleted <path>" for file_delete events', () => {
        const eventTs = new Date().toISOString();
        setupMocks({
            sessionRows: [],
            liveEventRows: [{ id: 52, project: 'fivo-cell', event_type: 'file_delete', file_path: 'src/old.ts', created_at: eventTs }],
        });
        const ctx = (0, prompt_builder_1.buildContext)('fivo-cell', 'claude-code');
        const out = (0, prompt_builder_1.formatContextForTool)(ctx, 'claude-code');
        expect(out).toContain('Live: deleted src/old.ts');
    });
    it('prefers lastSession over lastLiveFile when both exist (session is richer context)', () => {
        const eventTs = new Date(Date.now() - 30_000).toISOString();
        setupMocks({
            sessionRows: [{
                    id: 5, tool_name: 'cursor', project: 'fivo-cell',
                    start_time: new Date(Date.now() - 600_000).toISOString(),
                    end_time: new Date().toISOString(),
                    files_touched: '["src/session-tracker.ts"]',
                    key_decisions: '["Phase 2"]',
                    context_snapshot: 'Working on session data',
                }],
            liveEventRows: [{ id: 100, project: 'fivo-cell', event_type: 'file_save', file_path: 'src/recent.ts', created_at: eventTs }],
        });
        const ctx = (0, prompt_builder_1.buildContext)('fivo-cell', 'claude-code');
        expect(ctx.lastSession).toBeDefined();
        expect(ctx.lastLiveFile).toBeDefined();
        const out = (0, prompt_builder_1.formatContextForTool)(ctx, 'claude-code');
        expect(out).toContain('Tool: cursor');
        expect(out).toContain('Working on: Working on session data');
        // Should NOT show the live fallback when a session exists
        expect(out).not.toContain('Live: saved');
    });
    it('shows cold-start message when neither session nor live events exist', () => {
        setupMocks({ sessionRows: [], liveEventRows: [] });
        const ctx = (0, prompt_builder_1.buildContext)('unknown-project', 'claude-code');
        expect(ctx.lastSession).toBeUndefined();
        expect(ctx.lastLiveFile).toBeUndefined();
        const out = (0, prompt_builder_1.formatContextForTool)(ctx, 'claude-code');
        expect(out).toContain('(no session yet — first run)');
    });
    it('handles live_events query failure gracefully (returns undefined, does not crash)', () => {
        setupMocks({ sessionRows: [] });
        mockDb.prepare.mockImplementation((sql) => {
            if (sql.trim().toUpperCase().startsWith('SELECT * FROM LIVE_EVENTS')) {
                throw new Error('table missing');
            }
            return fakeStmt([]);
        });
        const ctx = (0, prompt_builder_1.buildContext)('fivo-cell', 'claude-code');
        expect(ctx.lastLiveFile).toBeUndefined();
    });
});
//# sourceMappingURL=atcell-live-fallback.test.js.map