"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 database_1 = require("../walls/06-memory/database/database");
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
// Pre-Launch Reality Check — Tests 1, 3, 5, 6
// These tests prove that the data backing `cell status --session` and
// `cell status --decisions` is queryable, well-formed, and survives restart.
const TMP_HOME = path.join(os.tmpdir(), 'fivo-cell-prelaunch-' + Date.now());
const REAL_HOME = process.env.USERPROFILE || process.env.HOME || '';
process.env.USERPROFILE = TMP_HOME;
process.env.HOME = TMP_HOME;
const behavioral_tracker_1 = require("../walls/03-knowledge/decisions/behavioral-tracker");
beforeAll(() => {
    fs.mkdirSync(TMP_HOME, { recursive: true });
    (0, database_1.initializeDatabase)();
    (0, behavioral_tracker_1.initBehaviorTables)();
});
afterAll(() => {
    try {
        fs.rmSync(TMP_HOME, { recursive: true, force: true });
    }
    catch { }
    process.env.USERPROFILE = REAL_HOME;
    process.env.HOME = REAL_HOME;
});
describe('Pre-Launch Test 1: cell status --session', () => {
    it('returns last touched file with timestamp', () => {
        const db = (0, database_1.getDb)();
        // Simulate a file save event being recorded
        db.prepare(`
      INSERT INTO session_files (project, file_path, touch_count, first_touched, last_touched)
      VALUES (?, ?, 3, datetime('now', '-5 minutes'), datetime('now'))
    `).run('prelaunch-test', 'src/server.ts');
        const last = (0, behavioral_tracker_1.getLastTouchedFile)('prelaunch-test');
        expect(last).not.toBeNull();
        expect(last?.file).toBe('src/server.ts');
        expect(last?.touchCount).toBe(3);
    });
    it('returns null when no files touched', () => {
        const last = (0, behavioral_tracker_1.getLastTouchedFile)('no-such-project-ever');
        expect(last).toBeNull();
    });
    it('returns most-recent when multiple files exist', () => {
        const db = (0, database_1.getDb)();
        db.prepare(`DELETE FROM session_files WHERE project = 'multi-file-test'`).run();
        db.prepare(`
      INSERT INTO session_files (project, file_path, touch_count, first_touched, last_touched)
      VALUES
        ('multi-file-test', 'src/old.ts', 1, datetime('now', '-1 hour'), datetime('now', '-1 hour')),
        ('multi-file-test', 'src/new.ts', 2, datetime('now'), datetime('now'))
    `).run();
        const last = (0, behavioral_tracker_1.getLastTouchedFile)('multi-file-test');
        expect(last?.file).toBe('src/new.ts');
    });
    it('counts detected patterns', () => {
        const db = (0, database_1.getDb)();
        db.prepare(`DELETE FROM code_patterns WHERE project = 'pattern-test'`).run();
        db.prepare(`
      INSERT INTO code_patterns (project, file_path, pattern_type, pattern_value, category, count, trust_score, language)
      VALUES
        ('pattern-test', 'a.ts', 'quote', 'single', 'style', 50, 90, 'ts'),
        ('pattern-test', 'a.ts', 'semi', 'always', 'style', 50, 90, 'ts'),
        ('pattern-test', 'b.ts', 'blind', 'no-try-catch', 'blind_spots', 5, 80, 'ts')
    `).run();
        const counts = (0, behavioral_tracker_1.getPatternCounts)('pattern-test');
        expect(counts.total).toBe(3);
        expect(counts.byCategory.style).toBe(2);
        expect(counts.byCategory.blind_spots).toBe(1);
    });
    it('exposes current context from logContext', () => {
        (0, behavioral_tracker_1.logContext)({ project: 'ctx-test', task: 'fixing blind spots', files: ['a.ts', 'b.ts'] });
        const summary = (0, behavioral_tracker_1.getBehaviorSummary)('ctx-test');
        expect(summary.currentContext?.task).toBe('fixing blind spots');
        expect(summary.currentContext?.files).toEqual(['a.ts', 'b.ts']);
    });
});
describe('Pre-Launch Test 3: cell status --decisions', () => {
    it('returns last 5 decisions with ago + worked flag', () => {
        const proj = 'decisions-test';
        // Insert with explicit, spaced-out timestamps to guarantee ordering
        const db = (0, database_1.getDb)();
        db.prepare(`DELETE FROM decision_log WHERE project = ?`).run(proj);
        db.prepare(`
      INSERT INTO decision_log (project, file_path, decision, worked, decided_at)
      VALUES
        (?, 'a.ts', 'used better-sqlite3 for cross-platform compat', 1, datetime('now', '-3 minutes')),
        (?, 'b.ts', 'skipped ts-node for ESM', 0, datetime('now', '-2 minutes')),
        (?, 'server.ts', 'added outer try/catch in server.ts', 1, datetime('now', '-1 minute'))
    `).run(proj, proj, proj);
        const recent = (0, behavioral_tracker_1.getRecentDecisionsWithAgo)(proj, 5);
        expect(recent.length).toBe(3);
        // Most recent first
        expect(recent[0].decision).toContain('outer try/catch');
        expect(recent[0].worked).toBe(true);
        expect(recent[0].ago).toMatch(/second|minute|hour/);
    });
    it('worked=true renders as Accepted, worked=false as Rejected', () => {
        const proj = 'verdict-test';
        const db = (0, database_1.getDb)();
        db.prepare(`DELETE FROM decision_log WHERE project = ?`).run(proj);
        db.prepare(`
      INSERT INTO decision_log (project, decision, worked, decided_at)
      VALUES
        (?, 'good choice', 1, datetime('now', '-2 minutes')),
        (?, 'bad choice', 0, datetime('now', '-1 minute'))
    `).run(proj, proj);
        const recent = (0, behavioral_tracker_1.getRecentDecisionsWithAgo)(proj, 5);
        const accepted = recent.find(r => r.decision === 'good choice');
        const rejected = recent.find(r => r.decision === 'bad choice');
        expect(accepted?.worked).toBe(true);
        expect(rejected?.worked).toBe(false);
    });
    it('returns empty array for unknown project', () => {
        const recent = (0, behavioral_tracker_1.getRecentDecisionsWithAgo)('no-such-project-' + Date.now());
        expect(recent).toEqual([]);
    });
    it('summary exposes totalDecisions count', () => {
        const proj = 'count-test';
        (0, behavioral_tracker_1.logDecision)({ project: proj, decision: 'one', worked: true });
        (0, behavioral_tracker_1.logDecision)({ project: proj, decision: 'two', worked: false });
        (0, behavioral_tracker_1.logDecision)({ project: proj, decision: 'three', worked: true });
        const summary = (0, behavioral_tracker_1.getBehaviorSummary)(proj);
        expect(summary.totalDecisions).toBeGreaterThanOrEqual(3);
    });
});
describe('Pre-Launch Test 6: restart persistence', () => {
    it('decisions survive a fresh summary call (SQLite-backed)', () => {
        const proj = 'persist-test';
        (0, behavioral_tracker_1.logDecision)({ project: proj, decision: 'persistent decision', worked: true });
        // Call summary multiple times to simulate restarts
        const s1 = (0, behavioral_tracker_1.getBehaviorSummary)(proj);
        const s2 = (0, behavioral_tracker_1.getBehaviorSummary)(proj);
        expect(s1.totalDecisions).toBe(s2.totalDecisions);
        expect(s1.totalDecisions).toBeGreaterThanOrEqual(1);
    });
});
//# sourceMappingURL=prelaunch-reality-check.test.js.map