"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 os = __importStar(require("os"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
describe('Phase 6: Usage Intelligence Store', () => {
    let tmpHome;
    let originalUserProfile;
    let closeDb;
    beforeAll(() => {
        originalUserProfile = process.env.USERPROFILE;
        tmpHome = path.join(os.tmpdir(), 'fivo-cell-phase6-' + Date.now());
        process.env.USERPROFILE = tmpHome;
        fs.mkdirSync(tmpHome, { recursive: true });
        const db = require('../walls/06-memory/database/database');
        closeDb = db.closeDb;
        closeDb();
    });
    beforeEach(() => {
        const { getDb } = require('../walls/06-memory/database/database');
        const db = getDb();
        db.prepare('DELETE FROM decision_outcomes').run();
        db.prepare('DELETE FROM repeat_mistake_alerts').run();
        db.prepare('DELETE FROM productivity_signals').run();
        db.prepare('DELETE FROM error_log').run();
        db.prepare('DELETE FROM sessions').run();
        db.prepare('DELETE FROM model_profiles').run();
        db.prepare('DELETE FROM model_interactions').run();
        db.prepare('DELETE FROM tech_proficiency').run();
    });
    afterAll(() => {
        if (originalUserProfile !== undefined) {
            process.env.USERPROFILE = originalUserProfile;
        }
        else {
            delete process.env.USERPROFILE;
        }
        closeDb();
        try {
            fs.rmSync(tmpHome, { recursive: true, force: true });
        }
        catch { }
    });
    describe('6.2: Decision History with Outcomes', () => {
        it('logs decision and retrieves it', async () => {
            const { logDecisionOutcome, getDecisionOutcomes } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            logDecisionOutcome({
                project: 'test-6',
                technology: 'TypeScript',
                reason: 'Type safety',
                outcome: 'Caught many bugs',
                wasRight: true,
                confidence: 80,
            });
            const decisions = getDecisionOutcomes('test-6');
            expect(decisions.length).toBe(1);
            expect(decisions[0].technology).toBe('TypeScript');
            expect(decisions[0].wasRight).toBe(true);
        });
        it('detects "always regret" pattern', async () => {
            const { logDecisionOutcome, getDecisionPatterns } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            for (let i = 0; i < 3; i++) {
                logDecisionOutcome({
                    project: 'test-6', technology: 'MongoDB', reason: 'flexible', outcome: 'pain', wasRight: false,
                });
            }
            const patterns = getDecisionPatterns('test-6');
            const mongo = patterns.find(p => p.technology === 'MongoDB');
            expect(mongo).toBeDefined();
            expect(mongo.timesChosen).toBe(3);
            expect(mongo.timesWrong).toBe(3);
            expect(mongo.advice).toContain('STOP');
        });
        it('detects "great choice" pattern', async () => {
            const { logDecisionOutcome, getDecisionPatterns } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            for (let i = 0; i < 4; i++) {
                logDecisionOutcome({
                    project: 'test-6', technology: 'SQLite', reason: 'simple', outcome: 'works', wasRight: true,
                });
            }
            const patterns = getDecisionPatterns('test-6');
            const sqlite = patterns.find(p => p.technology === 'SQLite');
            expect(sqlite).toBeDefined();
            expect(sqlite.advice).toContain('great choice');
        });
    });
    describe('6.3: Repeat Mistakes Map', () => {
        it('detects repeated error types in same file', async () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            for (let i = 0; i < 3; i++) {
                db.prepare('INSERT INTO error_log (project, file_path, error_type, occurred_at) VALUES (?, ?, ?, datetime(\'now\'))')
                    .run('test-6', 'src/api/users.ts', 'null_check');
            }
            const { detectRepeatMistakes } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            const mistakes = detectRepeatMistakes('test-6');
            expect(mistakes.length).toBe(1);
            expect(mistakes[0].errorType).toBe('null_check');
            expect(mistakes[0].count).toBe(3);
            expect(mistakes[0].suggestion).toContain('optional chaining');
        });
        it('marks critical severity at 5+ occurrences', async () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            for (let i = 0; i < 5; i++) {
                db.prepare('INSERT INTO error_log (project, file_path, error_type, occurred_at) VALUES (?, ?, ?, datetime(\'now\'))')
                    .run('test-6', 'src/db.ts', 'n_plus_1');
            }
            const { detectRepeatMistakes } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            const mistakes = detectRepeatMistakes('test-6');
            expect(mistakes[0].severity).toBe('critical');
        });
        it('writes to alerts table for tracking', async () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            for (let i = 0; i < 2; i++) {
                db.prepare('INSERT INTO error_log (project, file_path, error_type, occurred_at) VALUES (?, ?, ?, datetime(\'now\'))')
                    .run('test-6', 'src/api.ts', 'validation');
            }
            const { detectRepeatMistakes } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            detectRepeatMistakes('test-6');
            const alert = db.prepare('SELECT * FROM repeat_mistake_alerts WHERE project = ?').get('test-6');
            expect(alert).toBeDefined();
            expect(alert.error_type).toBe('validation');
            expect(alert.occurrence_count).toBe(2);
        });
    });
    describe('6.5: AI Interaction Stats', () => {
        it('aggregates model_profiles + model_interactions', async () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            db.prepare('INSERT INTO model_profiles (model_name, acceptance_rate, rejection_rate, best_use_cases) VALUES (?, ?, ?, ?)')
                .run('gpt-4', 0.85, 0.15, JSON.stringify(['code-gen', 'refactor']));
            // 9 accepted, 1 rejected → 90% acceptance
            for (let i = 0; i < 9; i++) {
                db.prepare('INSERT INTO model_interactions (model_name, task_type, accepted, project) VALUES (?, ?, ?, ?)')
                    .run('gpt-4', 'code-gen', 1, 'test-6');
            }
            db.prepare('INSERT INTO model_interactions (model_name, task_type, accepted, project) VALUES (?, ?, ?, ?)')
                .run('gpt-4', 'code-gen', 0, 'test-6');
            const { getAIInteractionStats } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            const stats = getAIInteractionStats('test-6');
            const gpt = stats.find(s => s.modelName === 'gpt-4');
            expect(gpt).toBeDefined();
            expect(gpt.totalInteractions).toBe(10);
            expect(gpt.accepted).toBe(9);
            expect(gpt.rejected).toBe(1);
            expect(gpt.recommendation).toContain('Strong match');
        });
    });
    describe('6.4: Productivity Signals', () => {
        it('flow state: many files, low switches, long duration', async () => {
            const { logProductivitySignal, getProductivitySignals } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            logProductivitySignal({ project: 'test-6', signalType: 'flow', durationMinutes: 120, filesTouched: 8, contextSwitches: 1 });
            const signals = getProductivitySignals('test-6', 30);
            expect(signals.length).toBe(1);
            // flow = 8*5 + 120/2 - 1*3 = 40 + 60 - 3 = 97
            expect(signals[0].flowScore).toBeGreaterThan(50);
            expect(signals[0].recommendation).toContain('Strong flow');
        });
        it('friction: many switches, few files', async () => {
            const { logProductivitySignal, getProductivitySignals } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            logProductivitySignal({ project: 'test-6', signalType: 'friction', durationMinutes: 30, filesTouched: 2, contextSwitches: 12 });
            const signals = getProductivitySignals('test-6', 30);
            // friction = 12*8 - 2*2 = 96 - 4 = 92
            expect(signals[0].frictionScore).toBeGreaterThan(50);
        });
    });
    describe('6.6: Skill Progression', () => {
        it('classifies improving vs regressing', async () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            // Tech with proficiency
            db.prepare('INSERT INTO tech_proficiency (project, technology, signals_count, proficiency_score) VALUES (?, ?, ?, ?)')
                .run('test-6', 'TypeScript', 50, 85);
            // Old errors (90 days ago)
            for (let i = 0; i < 10; i++) {
                db.prepare('INSERT INTO error_log (project, file_path, error_type, occurred_at) VALUES (?, ?, ?, datetime(\'now\', \'-90 days\'))')
                    .run('test-6', 'src/a.ts', 'type_error');
            }
            // Recent errors (last 30d) — fewer
            for (let i = 0; i < 2; i++) {
                db.prepare('INSERT INTO error_log (project, file_path, error_type, occurred_at) VALUES (?, ?, ?, datetime(\'now\', \'-5 days\'))')
                    .run('test-6', 'src/b.ts', 'type_error');
            }
            const { getSkillProgression } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            const skills = getSkillProgression('test-6');
            const ts = skills.find(s => s.technology === 'TypeScript');
            expect(ts).toBeDefined();
            expect(ts.trend).toBe('improving');
        });
    });
    describe('6.4: Burnout Detection', () => {
        it('flags high risk with long sessions + high friction', async () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            // Create long session (4 hours)
            db.prepare('INSERT INTO sessions (project, tool_name, start_time, end_time) VALUES (?, ?, datetime(\'now\', \'-4 hours\'), datetime(\'now\'))')
                .run('test-6', 'claude-code');
            // High friction signal
            db.prepare('INSERT INTO productivity_signals (project, signal_type, duration_minutes, files_touched, context_switches, friction_score, created_at) VALUES (?, ?, ?, ?, ?, ?, datetime(\'now\'))')
                .run('test-6', 'friction', 60, 1, 15, 80);
            const { getBurnoutSignals } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            const burnout = getBurnoutSignals('test-6');
            expect(burnout.risk).toMatch(/medium|high/);
            expect(burnout.signals.length).toBeGreaterThan(0);
        });
        it('low risk for healthy patterns', async () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            // Healthy: short session, low friction
            const { logProductivitySignal } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            logProductivitySignal({ project: 'test-6', signalType: 'flow', durationMinutes: 30, filesTouched: 5, contextSwitches: 1 });
            const { getBurnoutSignals } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            const burnout = getBurnoutSignals('test-6');
            expect(burnout.risk).toBe('low');
        });
    });
    describe('Combined Dashboard', () => {
        it('returns all sections in one call', async () => {
            const { logDecisionOutcome, getUsageDashboard } = await Promise.resolve().then(() => __importStar(require('../walls/06-memory/stores/usage-intelligence-store')));
            logDecisionOutcome({ project: 'test-6', technology: 'TS', reason: 'r', outcome: 'o', wasRight: true });
            const dash = getUsageDashboard('test-6');
            expect(dash.decisions.total).toBe(1);
            expect(dash.ai).toBeDefined();
            expect(dash.productivity).toBeDefined();
            expect(dash.skills).toBeDefined();
            expect(dash.burnout).toBeDefined();
            expect(dash.generatedAt).toBeDefined();
        });
    });
});
//# sourceMappingURL=usage-intelligence-store.test.js.map