"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.login = login;
exports.loadJwt = loadJwt;
exports.checkJwt = checkJwt;
const http_1 = __importDefault(require("./utils/http"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const utils_1 = require("./utils");
const config_1 = require("./config");
const KnowhowClient_1 = require("./services/KnowhowClient");
const browserLogin_1 = require("./auth/browserLogin");
async function login(jwtFlag) {
    if (!KnowhowClient_1.KNOWHOW_API_URL) {
        throw new Error("Error: KNOWHOW_API_URL environment variable not set.");
    }
    if (jwtFlag) {
        const jwt = await (0, utils_1.ask)("Enter your JWT: ");
        const configDir = path_1.default.join(process.cwd(), ".knowhow");
        const jwtFile = path_1.default.join(process.cwd(), ".knowhow", ".jwt");
        if (!fs_1.default.existsSync(configDir)) {
            fs_1.default.mkdirSync(configDir, { recursive: true });
        }
        fs_1.default.writeFileSync(jwtFile, jwt);
        fs_1.default.chmodSync(jwtFile, 0o600);
        console.log("JWT updated successfully.");
    }
    else {
        console.log("Starting browser-based authentication...");
        try {
            const existingConfig = await (0, config_1.getConfig)();
            const existingOrgId = existingConfig?.orgId;
            const browserLoginService = new browserLogin_1.BrowserLoginService(undefined, existingOrgId);
            await browserLoginService.login();
            console.log("Successfully authenticated via browser!");
        }
        catch (error) {
            console.error("Browser authentication failed:", error.message);
            console.log("You can try manual JWT login with: knowhow login --jwt");
            throw error;
        }
    }
    try {
        const storedJwt = await loadJwt();
        const { user, currentOrg } = await checkJwt(storedJwt);
        const orgId = currentOrg?.organizationId;
        console.log(`Current user: ${user.email}, \nOrganization: ${currentOrg?.organization?.name} - ${currentOrg?.organization?.id}`);
        const config = await (0, config_1.getConfig)();
        if (!config.modelProviders) {
            config.modelProviders = [];
        }
        const hasProvider = config.modelProviders.find((provider) => provider.provider === "knowhow");
        if (!hasProvider) {
            config.modelProviders.push({
                provider: "knowhow",
            });
        }
        if (orgId) {
            config.orgId = orgId;
        }
        await (0, config_1.updateConfig)(config);
    }
    catch (error) {
        if (http_1.default.isHttpError(error) && error.response) {
            const errData = await error.response.json().catch(() => ({ message: "Unknown error" }));
            throw new Error(`Error: ${error.status} - ${errData.message || "Unknown error"}`);
        }
        console.log("Error: Unable to fetch user information. Please check your JWT and try again.", error);
    }
}
async function loadJwt() {
    const jwtFile = path_1.default.join(process.cwd(), ".knowhow", ".jwt");
    if (!fs_1.default.existsSync(jwtFile)) {
        throw new Error("Error: JWT file not found.");
    }
    const jwt = fs_1.default.readFileSync(jwtFile, "utf-8").trim();
    if (!jwt) {
        throw new Error("Error: JWT is empty. Re-login with knowhow login --jwt.");
    }
    return jwt;
}
async function checkJwt(storedJwt) {
    const response = await http_1.default.get(`${KnowhowClient_1.KNOWHOW_API_URL}/api/users/me`, {
        headers: {
            Authorization: `Bearer ${storedJwt}`,
        },
    });
    const user = response.data.user;
    const orgs = user.orgs;
    const orgId = response.data.orgId;
    const currentOrg = orgs.find((org) => {
        return org.organizationId === orgId;
    });
    return { user, currentOrg };
}
//# sourceMappingURL=login.js.map