"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SignalCapture = void 0;
exports.getPersistedSignalCount = getPersistedSignalCount;
exports.getPersistedSignalsByType = getPersistedSignalsByType;
exports.getPersistedSignalsByProject = getPersistedSignalsByProject;
const types_1 = require("../../../types");
const crypto_1 = require("crypto");
const database_1 = require("../../06-memory/database/database");
class SignalCapture {
    signals = [];
    currentSessionId;
    lastActivityTime;
    sessionGapMs;
    constructor(sessionGapMinutes = 30) {
        this.currentSessionId = this.generateSessionId();
        this.lastActivityTime = Date.now();
        this.sessionGapMs = sessionGapMinutes * 60 * 1000;
    }
    captureEditDiff(originalCode, editedCode, context) {
        return this.createSignal('edit_diff', originalCode, editedCode, context);
    }
    captureAccept(originalCode, context) {
        return this.createSignal('accept', originalCode, '', context);
    }
    captureReject(originalCode, context) {
        return this.createSignal('reject', originalCode, '', context);
    }
    captureRetry(originalCode, context) {
        return this.createSignal('retry', originalCode, '', context);
    }
    getAllSignals() {
        return [...this.signals];
    }
    getSignalsByType(type) {
        return this.signals.filter((s) => s.type === type);
    }
    getSignalsBySession(sessionId) {
        return this.signals.filter((s) => s.sessionId === sessionId);
    }
    getCurrentSessionId() {
        return this.currentSessionId;
    }
    getSignalCount() {
        return this.signals.length;
    }
    clear() {
        this.signals = [];
    }
    createSignal(type, originalCode, editedCode, context) {
        this.checkSessionBoundary();
        const signal = {
            id: (0, crypto_1.randomUUID)(),
            type,
            timestamp: Date.now(),
            sessionId: this.currentSessionId,
            originalCode,
            editedCode,
            weight: types_1.SIGNAL_WEIGHTS[type],
            context,
        };
        this.signals.push(signal);
        if (this.signals.length > 10000) {
            this.signals.splice(0, this.signals.length - 10000);
        }
        this.lastActivityTime = signal.timestamp;
        this.persistSignal(signal);
        return signal;
    }
    persistSignal(signal) {
        try {
            const db = (0, database_1.getDb)();
            db.prepare(`INSERT OR REPLACE INTO signals (id, signal_type, file_path, diff, pattern_ids, project, session_id, weight, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
                .run(signal.id, signal.type, signal.context?.fileType || null, this.truncateDiff(signal.originalCode, signal.editedCode), null, signal.context?.projectId || null, signal.sessionId, signal.weight, new Date(signal.timestamp).toISOString());
        }
        catch {
            // DB persistence is best-effort; memory signals are the primary store
        }
    }
    truncateDiff(original, edited) {
        const raw = `--- original\n${original.slice(0, 500)}\n+++ edited\n${edited.slice(0, 500)}`;
        return raw.length > 2000 ? raw.slice(0, 2000) + '\n... [truncated]' : raw;
    }
    checkSessionBoundary() {
        const now = Date.now();
        if (now - this.lastActivityTime > this.sessionGapMs) {
            this.currentSessionId = this.generateSessionId();
        }
    }
    generateSessionId() {
        return `session_${Date.now()}_${(0, crypto_1.randomUUID)().substring(0, 8)}`;
    }
}
exports.SignalCapture = SignalCapture;
function getPersistedSignalCount() {
    try {
        const db = (0, database_1.getDb)();
        const row = db.prepare('SELECT COUNT(*) as count FROM signals').get();
        return row.count;
    }
    catch {
        return 0;
    }
}
function getPersistedSignalsByType(type) {
    try {
        const db = (0, database_1.getDb)();
        const rows = db.prepare('SELECT * FROM signals WHERE signal_type = ? ORDER BY created_at DESC LIMIT 100').all(type);
        return rows.map(mapDbRowToSignal);
    }
    catch {
        return [];
    }
}
function getPersistedSignalsByProject(project) {
    try {
        const db = (0, database_1.getDb)();
        const rows = db.prepare('SELECT * FROM signals WHERE project = ? ORDER BY created_at DESC LIMIT 100').all(project);
        return rows.map(mapDbRowToSignal);
    }
    catch {
        return [];
    }
}
function mapDbRowToSignal(row) {
    return {
        id: row.id,
        type: row.signal_type,
        timestamp: new Date(row.created_at).getTime(),
        sessionId: row.session_id || '',
        originalCode: row.diff || '',
        editedCode: '',
        weight: row.weight || 1,
        context: {
            language: row.signal_type === 'edit_diff' ? 'typescript' : '',
            framework: '',
            fileType: row.file_path || '',
            strictness: 'medium',
            projectId: row.project || '',
        },
    };
}
//# sourceMappingURL=signal-capture.js.map