"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 () {
    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.addInitCommand = addInitCommand;
exports.addLoginCommand = addLoginCommand;
exports.addUpdateCommand = addUpdateCommand;
exports.addGenerateCommand = addGenerateCommand;
exports.addEmbedCommands = addEmbedCommands;
exports.addUploadCommand = addUploadCommand;
exports.addDownloadCommand = addDownloadCommand;
exports.addChatCommand = addChatCommand;
exports.addGithubCredentialsCommand = addGithubCredentialsCommand;
const child_process_1 = require("child_process");
const package_json_1 = require("../../package.json");
const logger_1 = require("../logger");
const index_1 = require("../index");
const config_1 = require("../config");
const login_1 = require("../login");
const KnowhowClient_1 = require("../services/KnowhowClient");
const chat_1 = require("../chat");
function addInitCommand(program) {
    program
        .command("init")
        .description("Initialize knowhow configuration")
        .action(async () => {
        await (0, config_1.init)();
    });
}
function addLoginCommand(program) {
    program
        .command("login")
        .description("Login to knowhow")
        .option("--jwt", "Use manual JWT input instead of browser login")
        .action(async (opts) => {
        await (0, login_1.login)(opts.jwt);
    });
}
function addUpdateCommand(program) {
    program
        .command("update")
        .description("Update knowhow to the latest version from npm")
        .action(async () => {
        try {
            console.log("🔄 Checking for knowhow updates...");
            console.log(`Current version: ${package_json_1.version}`);
            console.log("📦 Installing latest version from npm...");
            (0, child_process_1.execSync)("npm install -g @tyvm/knowhow@latest", {
                stdio: "inherit",
                encoding: "utf-8",
            });
            console.log("✓ knowhow has been updated successfully!");
            console.log("Run 'knowhow --version' to see the new version.");
        }
        catch (error) {
            console.error("Error updating knowhow:", error.message);
            process.exit(1);
        }
    });
}
function addGenerateCommand(program) {
    program
        .command("generate")
        .description("Generate documentation")
        .action(async () => {
        const { setupServices } = await Promise.resolve().then(() => __importStar(require("./services")));
        await setupServices();
        await (0, index_1.generate)();
    });
}
function addEmbedCommands(program) {
    program
        .command("embed")
        .description("Create embeddings")
        .action(async () => {
        const { setupServices } = await Promise.resolve().then(() => __importStar(require("./services")));
        await setupServices();
        await (0, index_1.embed)();
    });
    program
        .command("embed:purge")
        .description("Purge embeddings matching a glob pattern")
        .argument("<pattern>", "Glob pattern to match files for purging")
        .action(async (pattern) => {
        await (0, index_1.purge)(pattern);
    });
}
function addUploadCommand(program) {
    program
        .command("upload")
        .description("Upload data")
        .action(async () => {
        await (0, index_1.upload)();
    });
}
function addDownloadCommand(program) {
    program
        .command("download")
        .description("Download data")
        .action(async () => {
        await (0, index_1.download)();
    });
}
function addChatCommand(program) {
    program
        .command("chat")
        .description("Start new chat interface")
        .action(async () => {
        const { setupServices } = await Promise.resolve().then(() => __importStar(require("./services")));
        await setupServices();
        await (0, chat_1.startChat)();
    });
}
function addGithubCredentialsCommand(program) {
    program
        .command("github-credentials [action]")
        .description("Git credential helper for GitHub. Use as: git config credential.helper 'knowhow github-credentials'")
        .option("--repo <repo>", "Repository in owner/repo format (e.g. myorg/myrepo)")
        .action(async (action, options) => {
        logger_1.logger.silence();
        const client = new KnowhowClient_1.KnowhowSimpleClient();
        let repo = options.repo;
        if (action === "get") {
            const lines = [];
            const readline = await Promise.resolve().then(() => __importStar(require("readline")));
            const rl = readline.createInterface({
                input: process.stdin,
                terminal: false,
            });
            await new Promise((resolve) => {
                rl.on("line", (line) => {
                    if (line.trim())
                        lines.push(line.trim());
                });
                rl.on("close", resolve);
            });
        }
        else if (action === "store" || action === "erase") {
            process.exit(0);
        }
        if (!repo) {
            try {
                const remoteUrl = (0, child_process_1.execSync)("git remote get-url origin", {
                    encoding: "utf-8",
                    stdio: ["pipe", "pipe", "pipe"],
                }).trim();
                const match = remoteUrl.match(/github\.com[/:]([^/]+\/[^/]+?)(?:\.git)?$/) ||
                    remoteUrl.match(/github\.com\/([^/]+\/[^/]+)/);
                if (match) {
                    repo = match[1];
                }
            }
            catch {
            }
        }
        try {
            const credential = await client.getGitCredential(repo || "");
            process.stdout.write(`protocol=${credential.protocol}\nhost=${credential.host}\nusername=${credential.username}\npassword=${credential.password}\n`);
        }
        catch (error) {
            console.error("Failed to get git credentials:", error.message);
            process.exit(1);
        }
    });
}
//# sourceMappingURL=misc.js.map