"use strict";
// Check if ~/.apptile-cli exists. If it doesn't create it and add workspaces table.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.db = void 0;
exports.createChat = createChat;
exports.getChat = getChat;
exports.toInMemoryChatMessage = toInMemoryChatMessage;
exports.toAnthropicMessages = toAnthropicMessages;
exports.toAmazonMessages = toAmazonMessages;
exports.toOpenaiMessages = toOpenaiMessages;
exports.getChatMessages = getChatMessages;
exports.sequenceToolCallsAndAddEmptyResults = sequenceToolCallsAndAddEmptyResults;
exports.sequenceToolCallAndResponses = sequenceToolCallAndResponses;
exports.persistChatMessage = persistChatMessage;
exports.createToolChatMessage = createToolChatMessage;
exports.getAPIKey = getAPIKey;
exports.deleteMetroProc = deleteMetroProc;
exports.getCurrentMetroProc = getCurrentMetroProc;
exports.createMetroProc = createMetroProc;
exports.createWorkspace = createWorkspace;
exports.deleteLink = deleteLink;
exports.getWorkspaces = getWorkspaces;
exports.getWorkspace = getWorkspace;
exports.getWorkspaceByLocation = getWorkspaceByLocation;
exports.insertOrUpdateOpenapp = insertOrUpdateOpenapp;
exports.getOpenApp = getOpenApp;
exports.closeAppByLocation = closeAppByLocation;
exports.getChatsByAppId = getChatsByAppId;
exports.getImagesFromPlanner = getImagesFromPlanner;
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const fs_1 = require("fs");
const types_1 = require("../ui/src/types");
const migrate_1 = require("./migrate");
const markdown_it_1 = __importDefault(require("markdown-it"));
const logger_1 = require("../utils/logger");
const chat_1 = __importDefault(require("../models/chat"));
const chatmessage_1 = __importDefault(require("../models/chatmessage"));
const md = (0, markdown_it_1.default)();
const isPostgresEnabled = process.env.ENABLE_POSTGRES == 'true';
const homeDir = os_1.default.homedir();
try {
    (0, fs_1.mkdirSync)(path_1.default.resolve(homeDir, '.apptile-cli'));
}
catch (err) {
    if ((err === null || err === void 0 ? void 0 : err.code) === 'EEXIST') {
        console.log("config folder already exists");
    }
    else {
        throw err;
    }
}
const dbFilePath = path_1.default.resolve(homeDir, '.apptile-cli/db.sqlite');
exports.db = new better_sqlite3_1.default(dbFilePath); // , { verbose: console.log });
(0, migrate_1.runMigrations)(exports.db);
function narrowChat(raw) {
    return (raw &&
        (typeof raw.id === 'number') &&
        (typeof raw.outputFile === 'string') &&
        (['widget', 'datasource', 'app'].includes(raw.type)) &&
        (typeof raw.createdAt === 'string' || typeof raw.createdAt === 'object') &&
        (["openai", "claude", "google", "amazon"].includes(raw.llm_provider)) &&
        (typeof raw.llm_model === "string"));
}
function narrowChatArray(raw) {
    try {
        let result = true;
        for (let i = 0; i < raw.length; ++i) {
            result = result && narrowChat(raw[i]);
        }
        return result;
    }
    catch (err) {
        console.error("Failed to validate chat array", err);
        return false;
    }
}
const selectChat = exports.db.prepare(`SELECT * FROM chat WHERE id = ?`);
const insertChat = exports.db.prepare(`INSERT INTO chat (outputFile, type, llm_provider, llm_model, appId) VALUES (?,?,?,?,?)`);
function createChat(filePath, type, provider, model, appId) {
    return __awaiter(this, void 0, void 0, function* () {
        let chat;
        if (isPostgresEnabled) {
            const insertChatData = yield chat_1.default.create({
                outputFile: filePath,
                type,
                llm_provider: provider,
                llm_model: model,
                appId
            });
            chat = insertChatData.get({ plain: true });
        }
        else {
            const { lastInsertRowid } = insertChat.run(filePath, type, provider, model, appId);
            chat = selectChat.get(lastInsertRowid);
            console.log("Creating new chat: ", chat);
        }
        if (narrowChat(chat)) {
            return chat;
        }
        else {
            return null;
        }
    });
}
const selectChatForArtefact = exports.db.prepare(`SELECT * FROM chat WHERE outputFile = ?`);
function getChat(filePath) {
    return __awaiter(this, void 0, void 0, function* () {
        let chat;
        if (isPostgresEnabled) {
            chat = yield chat_1.default.findOne({
                where: {
                    outputFile: filePath
                }
            });
        }
        else {
            chat = selectChatForArtefact.get(filePath);
        }
        if (chat && narrowChat(chat)) {
            return chat;
        }
        else {
            return null;
        }
    });
}
;
function toInMemoryChatMessage(messages) {
    return messages.map(it => {
        return {
            role: it.role,
            content_type: it.content_type,
            content: it.content,
            tool_call_id: it.tool_call_id,
            tool_name: it.tool_name,
            temp_id: it.temp_id
        };
    });
}
function isImageMedia(mimetype) {
    return ["image/png", "image/jpeg"].includes(mimetype);
}
function toAnthropicMessages(messages) {
    let result = [];
    for (let i = 0; i < messages.length; ++i) {
        let message = messages[i];
        let transformedMessage = null;
        if (message.role === "assistant") {
            if (message.content_type === "text") {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            type: "text",
                            text: message.content
                        }
                    ]
                };
            }
            else if (message.content_type === "tool_use" &&
                message.tool_name &&
                message.content &&
                message.tool_call_id) {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            type: "tool_use",
                            id: message.tool_call_id,
                            name: message.tool_name,
                            input: JSON.parse(message.content)
                        }
                    ]
                };
            }
            else {
                logger_1.logger.error("Cannot process this assistant message: ");
            }
        }
        else if (message.role === "user") {
            if (message.content_type === "text") {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            type: "text",
                            text: message.content
                        }
                    ]
                };
            }
            else if (message.content_type === "tool_result" && message.tool_call_id) {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            type: "tool_result",
                            tool_use_id: message.tool_call_id,
                            content: message.content
                        }
                    ]
                };
            }
            else if (isImageMedia(message.content_type)) {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            type: "image",
                            source: {
                                type: "base64",
                                media_type: message.content_type,
                                data: message.content
                            }
                        }
                    ]
                };
            }
            else {
                logger_1.logger.error("Cannot process this tool user message: ");
            }
        }
        else {
            throw new Error("Unreachable codepath!");
        }
        if (transformedMessage) {
            result.push(transformedMessage);
        }
    }
    return result;
}
function base64ToUint8Array(base64) {
    const binaryStr = atob(base64);
    const len = binaryStr.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryStr.charCodeAt(i);
    }
    return bytes;
}
function toAmazonMessages(messages) {
    let result = [];
    for (let i = 0; i < messages.length; ++i) {
        let message = messages[i];
        let transformedMessage = null;
        if (message.role === "assistant") {
            if (message.content_type === "text") {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            text: message.content
                        }
                    ]
                };
            }
            else if (message.content_type === "tool_use" &&
                message.tool_name &&
                message.content &&
                message.tool_call_id) {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            toolUse: {
                                toolUseId: message.tool_call_id,
                                name: message.tool_name,
                                input: JSON.parse(message.content)
                            }
                        }
                    ]
                };
            }
            else {
                logger_1.logger.error("Cannot process this assistant message: ");
            }
        }
        else if (message.role === "user") {
            if (message.content_type === "text") {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            text: message.content
                        }
                    ]
                };
            }
            else if (message.content_type === "tool_result" && message.tool_call_id) {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            toolResult: {
                                toolUseId: message.tool_call_id,
                                content: [
                                    {
                                        text: message.content
                                    }
                                ]
                            }
                        }
                    ]
                };
            }
            else if (isImageMedia(message.content_type)) {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            image: {
                                format: message.content_type === "image/jpeg" ? "jpeg" : "png",
                                source: {
                                    bytes: base64ToUint8Array(message.content),
                                }
                            }
                        }
                    ]
                };
            }
            else {
                logger_1.logger.error("Cannot process this tool user message: ");
            }
        }
        else {
            throw new Error("Unreachable codepath!");
        }
        if (transformedMessage) {
            result.push(transformedMessage);
        }
    }
    return result;
}
function toOpenaiMessages(messages, systemPrompt) {
    let result = [];
    result.push({
        role: 'system',
        content: systemPrompt
    });
    for (let i = 0; i < messages.length; ++i) {
        let message = messages[i];
        let transformedMessage = null;
        if (message.role === "assistant") {
            if (message.content_type === "text") {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            type: "text",
                            text: message.content
                        }
                    ]
                };
            }
            else if (message.content_type === "tool_use" &&
                message.tool_name &&
                message.content &&
                message.tool_call_id) {
                transformedMessage = {
                    role: "assistant",
                    tool_calls: [{
                            id: message.tool_call_id,
                            type: "function",
                            function: {
                                name: message.tool_name,
                                arguments: message.content
                            }
                        }]
                };
            }
            else {
                logger_1.logger.error("Cannot process this assistant message: " + JSON.stringify(message));
            }
        }
        else if (message.role === "user") {
            if (message.content_type === "text") {
                transformedMessage = {
                    role: message.role,
                    content: [
                        {
                            type: "text",
                            text: message.content
                        }
                    ]
                };
            }
            else if (message.content_type === "tool_result" && message.tool_call_id) {
                transformedMessage = {
                    role: "tool",
                    tool_call_id: message.tool_call_id,
                    content: [
                        {
                            type: "text",
                            text: message.content
                        }
                    ]
                };
            }
            else {
                logger_1.logger.error("Cannot process this tool user message: " + JSON.stringify(message));
            }
        }
        else {
            throw new Error("Unreachable codepath!");
        }
        if (transformedMessage) {
            result.push(transformedMessage);
        }
    }
    return result;
}
function narrowChatMessage(raw) {
    try {
        return (raw &&
            (typeof raw.id === 'number') &&
            (typeof raw.chatId === 'number') &&
            (['user', 'assistant'].includes(raw.role)) &&
            (['text', 'tool_use', 'tool_result', 'text/plain', 'image/jpeg', 'image/png'].includes(raw.content_type)) &&
            (typeof raw.content === 'string') &&
            (!raw.tool_call_id || typeof raw.tool_call_id === 'string') &&
            (typeof raw.createdAt === 'string' || typeof raw.createdAt === 'object') &&
            (raw.htmlcontent === null || typeof raw.htmlcontent === 'string') &&
            (!raw.tool_name || typeof raw.tool_name === 'string'));
    }
    catch (err) {
        console.error("Failed to validate chat message: ", raw);
        return false;
    }
}
function narrowChatMessageArray(raw) {
    let result = false;
    try {
        result = Array.isArray(raw);
        for (let i = 0; i < raw.length; ++i) {
            result = result && narrowChatMessage(raw[i]);
        }
    }
    catch (err) {
        console.error("Failed to validate chat message array", err);
    }
    return result;
}
const selectMessagesByChatDesc = exports.db.prepare(`SELECT * FROM chat_message WHERE chatId = ? ORDER BY id DESC`);
const selectMessagesByChatAsc = exports.db.prepare(`SELECT * FROM chat_message WHERE chatId = ? ORDER BY id ASC`);
const selectMessagesByChatDescWithLimit = exports.db.prepare(`SELECT * FROM (SELECT * FROM chat_message WHERE chatId = ? ORDER BY id DESC LIMIT ?) ORDER BY id ASC`);
const selectMessagesByChatAscWithLimit = exports.db.prepare(`SELECT * FROM chat_message WHERE chatId = ? ORDER BY id ASC LIMIT ?`);
function getChatMessages(chatId, dateOrder, limit) {
    return __awaiter(this, void 0, void 0, function* () {
        let messages;
        if (isPostgresEnabled) {
            const options = {
                where: { chatId },
                order: [["id", dateOrder]],
                raw: true
            };
            if (limit) {
                options.limit = limit;
                options.subQuery = false;
            }
            messages = yield chatmessage_1.default.findAll(options);
            if (dateOrder == 'DESC' && limit) {
                messages.reverse();
            }
        }
        else {
            if (limit) {
                if (dateOrder === 'DESC') {
                    messages = selectMessagesByChatDescWithLimit.all(chatId, limit);
                }
                else {
                    messages = selectMessagesByChatAscWithLimit.all(chatId, limit);
                }
            }
            else {
                if (dateOrder === 'DESC') {
                    messages = selectMessagesByChatDesc.all(chatId);
                }
                else {
                    messages = selectMessagesByChatAsc.all(chatId);
                }
            }
        }
        if (narrowChatMessageArray(messages)) {
            return messages;
        }
        else {
            return [];
        }
    });
}
function sequenceToolCallsAndAddEmptyResults(messages) {
    let result = [];
    const toolCalls = {};
    // First pass: build mapping of tool calls and responses
    for (let i = 0; i < messages.length; ++i) {
        const current = messages[i];
        if (current.content_type === "tool_use" && current.tool_call_id) {
            toolCalls[current.tool_call_id] = Object.assign(Object.assign({}, toolCalls[current.tool_call_id]), { tool_call: current });
        }
        else if (current.content_type === "tool_result" && current.tool_call_id) {
            toolCalls[current.tool_call_id] = Object.assign(Object.assign({}, toolCalls[current.tool_call_id]), { tool_resp: current });
        }
    }
    // Second pass: sequence messages and add empty tool results where needed
    for (let i = 0; i < messages.length; ++i) {
        const current = messages[i];
        if (current.content_type === "tool_use") {
            if (current.tool_call_id) {
                result.push(current);
                if (toolCalls[current.tool_call_id].tool_resp) {
                    result.push(toolCalls[current.tool_call_id].tool_resp);
                }
                else {
                    // Add empty tool result if none exists
                    const emptyResult = Object.assign(Object.assign({}, current), { role: "user", content_type: "tool_result", content: " " });
                    result.push(emptyResult);
                    logger_1.logger.debug("Added empty tool_result for tool_call: " + JSON.stringify(current));
                }
            }
            else {
                logger_1.logger.error("Dropping tool_call that doesn't have an id: " + JSON.stringify(current));
            }
        }
        else if (current.content_type !== "tool_result") {
            result.push(current);
        }
    }
    return result;
}
function sequenceToolCallAndResponses(messages, includeIncompleteToolUse = false) {
    let result = [];
    const toolCalls = {};
    for (let i = 0; i < messages.length; ++i) {
        const current = messages[i];
        if (current.content_type === "tool_use" && current.tool_call_id) {
            toolCalls[current.tool_call_id] = Object.assign(Object.assign({}, toolCalls[current.tool_call_id]), { tool_call: current });
        }
        else if (current.content_type === "tool_result" && current.tool_call_id) {
            toolCalls[current.tool_call_id] = Object.assign(Object.assign({}, toolCalls[current.tool_call_id]), { tool_resp: current });
        }
    }
    for (let i = 0; i < messages.length; ++i) {
        const current = messages[i];
        if (current.content_type === "tool_use") {
            if (current.tool_call_id) {
                if (includeIncompleteToolUse) {
                    result.push(current);
                    if (toolCalls[current.tool_call_id].tool_resp) {
                        result.push(toolCalls[current.tool_call_id].tool_resp);
                    }
                }
                else if (toolCalls[current.tool_call_id].tool_resp) {
                    result.push(current);
                    result.push(toolCalls[current.tool_call_id].tool_resp);
                }
                else {
                    // logger.error("Dropping tool_call because tool_response does not exist: " + JSON.stringify(current));
                }
            }
            else {
                logger_1.logger.error("Dropping tool_call that doesn't have an id: " + JSON.stringify(current));
            }
        }
        else if (current.content_type !== "tool_result") {
            result.push(current);
        }
    }
    return result;
}
const insertChatWithContentAndRole = exports.db.prepare(`INSERT INTO chat_message (chatId, tool_call_id, tool_name, content_type, role, content, htmlcontent, temp_id) VALUES (?,?,?,?,?,?,?,?)`);
function persistChatMessage(chatId, tool_call_id, tool_name, content_type, role, content, temp_id) {
    return __awaiter(this, void 0, void 0, function* () {
        var _a;
        let htmlContent = "";
        if (role === "assistant") {
            try {
                const parsedmessage = (_a = JSON.parse(content)) === null || _a === void 0 ? void 0 : _a[0];
                if (parsedmessage.type === "tool_use") {
                    if (parsedmessage.name === "nocodelayer_generate_code_for_plugin") {
                        htmlContent = md.renderInline('Prompt for plugin agent to generate code for *`' + parsedmessage.input.name + '`*\n');
                        htmlContent += md.renderInline(parsedmessage.input.prompt);
                    }
                    else {
                        htmlContent = md.render('*Calling tool* `' + parsedmessage.name + '`\n' +
                            '```\n' + JSON.stringify(parsedmessage.input, null, 2) + '\n```');
                    }
                }
                else if (parsedmessage.type === "text") {
                    htmlContent = md.render(parsedmessage.text);
                }
            }
            catch (err) {
                try {
                    htmlContent = md.render(content);
                }
                catch (err) {
                    htmlContent = "";
                }
            }
        }
        else if (role === "user") {
            let processedContent = content;
            if (content.includes("image_included_in_next_message")) {
                processedContent = content.replace(/(?:&nbsp;)?`image_included_in_next_message`/g, '');
            }
            htmlContent = md.render(processedContent);
        }
        if (isPostgresEnabled) {
            yield chatmessage_1.default.create({
                chatId,
                tool_call_id: tool_call_id,
                tool_name: tool_name,
                content_type: content_type,
                role: role,
                content: content,
                htmlcontent: htmlContent,
                temp_id: temp_id
            });
        }
        else {
            insertChatWithContentAndRole.run(chatId, tool_call_id, tool_name, content_type, role, content, htmlContent, temp_id);
        }
    });
}
const insertToolCall = exports.db.prepare(`INSERT INTO chat_message (chatId, role, content, tool_call_id) VALUES (?,?,?,?)`);
function createToolChatMessage(chatId, role, content, tool_call_id) {
    return __awaiter(this, void 0, void 0, function* () {
        if (isPostgresEnabled) {
            yield chatmessage_1.default.create({
                chatId,
                role: role,
                content: content,
                tool_call_id: tool_call_id
            });
        }
        else {
            insertToolCall.run(chatId, role, content, tool_call_id);
        }
    });
}
function narrowAPIKey(raw) {
    try {
        if (raw &&
            (typeof raw.id === 'number') &&
            (["openai", "claude", "pexels", "google", "aws_access_key_id", "aws_secret_access_key"].includes(raw.type)) &&
            (typeof raw.apikey === 'string')) {
            return true;
        }
    }
    catch (err) {
        console.error("Failed to validate APIKey", err);
    }
    return false;
}
const selectAPIKey = exports.db.prepare(`SELECT * FROM apikey where type=?`);
function getAPIKey(type) {
    let key = selectAPIKey.get(type);
    if (narrowAPIKey(key)) {
        return key;
    }
    else {
        return null;
    }
}
function narrowMetroProc(raw) {
    try {
        return (typeof raw.pid === "number") &&
            (typeof raw.repoPath === "string");
    }
    catch (err) {
        console.error("Failed to narrow metro proc");
        return false;
    }
}
function narrowMetroProcArray(raw) {
    try {
        let result = true;
        for (let i = 0; i < raw.length; ++i) {
            result = result && narrowMetroProc(raw[i]);
        }
        return result;
    }
    catch (err) {
        console.error("Failed to validate metroProc array");
        return false;
    }
}
const delMetroProc = exports.db.prepare(`DELETE FROM metro WHERE repoPath=?`);
function deleteMetroProc(repoPath) {
    delMetroProc.run(repoPath);
}
const selectMetroProc = exports.db.prepare(`SELECT * FROM metro`);
function getCurrentMetroProc() {
    let procs = selectMetroProc.all();
    if (narrowMetroProcArray(procs)) {
        return procs;
    }
    else {
        return null;
    }
}
const insertMetroProc = exports.db.prepare(`INSERT INTO metro (pid, repoPath) VALUES (?,?)`);
function createMetroProc(pid, fullPath) {
    insertMetroProc.run(pid.toFixed(0), fullPath);
}
const insertWorkspace = exports.db.prepare(`INSERT INTO workspaces (location)
               VALUES (?)`);
function createWorkspace(location) {
    try {
        insertWorkspace.run(location);
    }
    catch (err) {
        console.error("Failed to create link", err);
    }
}
const removeWorkspace = exports.db.prepare(`DELETE FROM workspaces WHERE id = ?`);
function deleteLink(id) {
    removeWorkspace.run(id);
}
const getAllWorkspaces = exports.db.prepare(`SELECT * FROM workspaces`);
function getWorkspaces() {
    const workspaces = getAllWorkspaces.all();
    if (types_1.DataBase.narrowWorkspaceArray(workspaces)) {
        return workspaces;
    }
    else {
        console.error("Invalid link found in table", workspaces);
        return null;
    }
}
const findWorkspace = exports.db.prepare(`SELECT * FROM workspaces WHERE id = ?`);
function getWorkspace(id) {
    const workspace = findWorkspace.get(id.toFixed(0));
    if (types_1.DataBase.narrowWorkspace(workspace)) {
        return workspace;
    }
    else {
        console.error("Invalid workspace found in table", workspace);
        return null;
    }
}
const findWorkspaceByLocation = exports.db.prepare(`SELECT * FROM workspaces WHERE location = ?`);
function getWorkspaceByLocation(location) {
    const workspace = findWorkspaceByLocation.get(location);
    if (types_1.DataBase.narrowWorkspace(workspace)) {
        return workspace;
    }
    else {
        console.error("Invalid workspace found in table", workspace);
        return null;
    }
}
function narrowOpenedApp(result) {
    return ((result) &&
        (typeof (result.appId) === "string") &&
        (typeof (result.workspaceId === "string")) &&
        (typeof (result.repoPath) === "string") &&
        (!!result.repoPath) &&
        ((result.apptilecookie === null) || (typeof result.apptilecookie === "string")));
}
const insertOrUpdateOpenapps = exports.db.prepare(`INSERT INTO openapps (workspaceId, appId, repoPath) 
  VALUES (?, ?, ?)
  ON CONFLICT(appId)
  DO UPDATE SET 
    workspaceId = excluded.workspaceId,
    repoPath = excluded.repoPath
  `);
function insertOrUpdateOpenapp(workspaceId, appId, repoPath) {
    insertOrUpdateOpenapps.run(workspaceId, appId, repoPath);
}
const findOpenApp = exports.db.prepare(`SELECT * FROM openapps WHERE appId = ?`);
function getOpenApp(appId) {
    return __awaiter(this, void 0, void 0, function* () {
        const openedAppEntry = findOpenApp.get(appId);
        if (narrowOpenedApp(openedAppEntry)) {
            return openedAppEntry;
        }
        else {
            return null;
        }
    });
}
function closeAppByLocation(repoPath) {
    // No op function
    return () => { };
}
const selectChatsByAppId = exports.db.prepare(`SELECT * FROM chat WHERE appId = ?`);
function getChatsByAppId(appId) {
    return __awaiter(this, void 0, void 0, function* () {
        let chats;
        if (isPostgresEnabled) {
            chats = yield chat_1.default.findAll({ where: { appId } });
        }
        chats = selectChatsByAppId.all(appId);
        if (narrowChatArray(chats)) {
            return chats;
        }
        else {
            return [];
        }
    });
}
function narrowImages(imgs) {
    let result = true;
    for (let i = 0; i < imgs.length; ++i) {
        result = result && (typeof imgs[i].content === "string");
        result = result && (typeof imgs[i].content_type === "string");
    }
    return result;
}
const imagesFromPlanner = exports.db.prepare(`SELECT content, content_type FROM chat_message 
WHERE chatId IN (
	SELECT id FROM chat WHERE outputFile = ?
) AND content_type LIKE 'image/%'`);
function getImagesFromPlanner(appId) {
    const images = imagesFromPlanner.all(appId);
    if (narrowImages(images)) {
        return images;
    }
    else {
        return [];
    }
}
exports.default = exports.db;
