"use strict";
// WebSocket Server — wss:// real-time guardian stream
// TLS via mkcert, fallback to ws:// with token auth
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 });
exports.initWebSocket = initWebSocket;
exports.getDaemonSecret = getDaemonSecret;
const ws_1 = require("ws");
const crypto = __importStar(require("crypto"));
const realtime_guardian_1 = require("../../03-knowledge/decisions/realtime-guardian");
const clients = new Map();
let daemonSecret;
function initWebSocket(httpServer) {
    daemonSecret = crypto.randomBytes(32).toString('hex');
    const wss = new ws_1.WebSocketServer({ server: httpServer, path: '/ws' });
    wss.on('connection', (ws) => {
        const clientId = crypto.randomUUID();
        const client = { ws, token: '', authenticated: false };
        clients.set(clientId, client);
        ws.on('message', (data) => {
            try {
                const msg = JSON.parse(data.toString());
                if (msg.type === 'auth') {
                    const expectedToken = crypto.createHash('sha256').update(msg.deviceId + daemonSecret).digest('hex');
                    if (msg.token === expectedToken) {
                        client.token = msg.token;
                        client.authenticated = true;
                        ws.send(JSON.stringify({ type: 'auth_ok' }));
                    }
                    else {
                        ws.send(JSON.stringify({ type: 'auth_fail' }));
                        ws.close();
                    }
                    return;
                }
                if (!client.authenticated) {
                    ws.send(JSON.stringify({ type: 'error', message: 'not authenticated' }));
                    return;
                }
                if (msg.type === 'analyze') {
                    const alerts = (0, realtime_guardian_1.analyzeLine)(msg.code, msg.line);
                    if (alerts.length > 0)
                        ws.send(JSON.stringify({ type: 'alerts', alerts }));
                }
                if (msg.type === 'feedback') {
                    (0, realtime_guardian_1.recordFeedback)(msg.alertMessage, msg.helpful);
                }
            }
            catch {
                ws.send(JSON.stringify({ type: 'error', message: 'invalid message' }));
            }
        });
        ws.on('close', () => { clients.delete(clientId); });
    });
    return wss;
}
function getDaemonSecret() { return daemonSecret; }
//# sourceMappingURL=websocket.js.map