/*
 * Entry point to requests 
 * Created by: Michael Pastushkov <michael@pastushkov.com>
 */

const { v4: uuidv4 } = require('uuid');
const utils = require('../utils/utils');
const ConversationManager = require('./ConversationManager');

const MODEL = 'gpt-oss:20b'; // 'llama3:8b'; // 'gpt-oss:20b';
const EMBED_MODEL = 'nomic-embed-text';
const LABEL_MODEL = 'llama3:8b';

const sessions = new Map(); // cookie -> ConversationManager
//const queues = new Map(); // cookie -> Promise (to serialize)

async function run(req, res) {

    // First, let's handle the cookies to separate users (with no login)
    let cookie = req.cookies?.session;
    if (!cookie) {
        cookie = uuidv4();
        res.cookie('session', cookie, { path: '/', sameSite: 'Lax', httpOnly: true });
        utils.log(`[session] New cookie set: ${cookie}`, 5);
    } else {
        utils.log(`[session] Existing cookie: ${cookie}`, 5);
    }
    // Get conversation manager
    let convman = sessions.get(cookie);
    if (!convman) {
        convman = new ConversationManager(MODEL, EMBED_MODEL, LABEL_MODEL);
        sessions.set(cookie, convman);
    }

    // Begin (or continue) conversation
    await convman.ask(req.body.content, (line) => {
        process.stdout.write(line);
        res.write(`${line}`);
        res.flush();
    });

    res.end();
}

async function stop(req, res) {
    utils.log('stop');
    res.send('Stop OK');
}

async function clear(req, res) {
    res.clearCookie('session', { path: '/', sameSite: 'Lax', httpOnly: true });
    utils.log('clear');
    res.send('Clear OK');
}


module.exports = { run, stop };

/* Testing * /

function log(data) {
    console.log(data);
}

(async () => {
    await run('Сколько в мире котов и кошек?', '1', log);
    await run('Найди веб ссылки на материалы', '1', log);
})();

/**/

module.exports.run = run;
module.exports.stop = stop;
module.exports.clear = clear;
