#!/usr/bin/env node
"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const readlineSync = __importStar(require("readline-sync"));
const dotenv = __importStar(require("dotenv"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const openai_1 = require("openai");
const commander_1 = require("commander");
const ApplicationController_1 = require("./controllers/ApplicationController");
const program = new commander_1.Command();
// Define your command with options
program
    .option("--files <files...>", "Input files to process")
    .action(() => __awaiter(void 0, void 0, void 0, function* () {
    const options = program.opts();
    let filePaths = [];
    // determines if exists
    if (options.files) {
        filePaths = [...options.files];
    }
    // Define the path for your .env file
    const envPath = path.join(process.env.HOME, ".config", "shell-chat");
    const envFile = path.join(envPath, ".env");
    if (!fs.existsSync(envFile)) {
        fs.mkdirSync(envPath, { recursive: true });
        const apiKey = yield getAPIKey();
        yield writeSensibleDefaultsToEnv({ envFile, apiKey });
    }
    dotenv.config({ path: envFile });
    const app = new ApplicationController_1.ApplicationController(filePaths);
    app.run();
}));
program.parse(process.argv);
function getAPIKey() {
    return __awaiter(this, void 0, void 0, function* () {
        let apiKey = "";
        let isApiKeyValid = false;
        const validateAPIKey = (apiKey) => __awaiter(this, void 0, void 0, function* () {
            if (apiKey.length === 0) {
                return false;
            }
            const configuration = new openai_1.Configuration({
                apiKey: apiKey,
            });
            const openai = new openai_1.OpenAIApi(configuration);
            try {
                yield openai.listModels();
                return true;
            }
            catch (e) {
                return false;
            }
        });
        while (!isApiKeyValid) {
            // The hideEchoBack option masks user input
            apiKey = readlineSync.question("Please enter your OPENAI_API_KEY: ", {
                hideEchoBack: true,
            });
            // Here's a placeholder for your validation logic
            isApiKeyValid = yield validateAPIKey(apiKey);
            if (!isApiKeyValid) {
                console.log("Invalid API Key, please try again.");
            }
        }
        return apiKey;
    });
}
function writeSensibleDefaultsToEnv({ envFile, apiKey, }) {
    return __awaiter(this, void 0, void 0, function* () {
        const objContent = {
            OPENAI_API_KEY: apiKey,
            MODEL_NAME: "gpt-3.5-turbo-16k",
            MAX_TOKENS: 16000,
            MAX_COMPLETION_TOKENS: 500,
            RESERVED_INPUT_TOKENS: 250,
            RESERVED_CONVERSATION_TOKENS: 2000,
            RESERVED_ERROR_CORRECTION_TOKENS: 200,
        };
        const content = Object.entries(objContent).reduce((acc, [key, value]) => {
            acc += `${key}=${value}\n`;
            return acc;
        }, "");
        fs.writeFileSync(envFile, content, "utf8");
    });
}
