"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupCLI = setupCLI;
const commander_1 = require("commander");
const gemini_auth_1 = require("../auth/gemini-auth");
const antigravity_1 = require("../auth/antigravity");
const account_manager_1 = require("../accounts/account-manager");
const openai_compat_1 = require("../proxy/openai-compat");
const compressor_1 = require("../token-saver/compressor");
const relevance_1 = require("../token-saver/relevance");
const budget_1 = require("../token-saver/budget");
const ui_1 = require("../utils/ui");
const open_1 = __importDefault(require("open"));
const crypto_1 = __importDefault(require("crypto"));
async function setupCLI() {
    const program = new commander_1.Command();
    const accountManager = new account_manager_1.AccountManager({ autoRotate: true });
    const tokenCompressor = new compressor_1.TokenCompressor();
    const relevanceScorer = new relevance_1.RelevanceScorer();
    const tokenBudget = new budget_1.TokenBudgetManager(8000);
    program
        .name("frouter")
        .description("Agentic Gemini proxy with multi-account OAuth, token saving, and OpenAI-compatible API")
        .version("1.0.1");
    program
        .option("-p, --port <port>", "Port to run the proxy on", "20129")
        .option("-H, --host <host>", "Host to bind the proxy to", "0.0.0.0")
        .option("-n, --no-browser", "Do not open browser automatically")
        .option("-l, --log", "Show server logs")
        .option("-t, --tray", "Run in background tray")
        .option("--skip-update", "Skip auto-update check");
    program
        .command("add-account")
        .description("Add a new account via Google OAuth")
        .argument("<type>", "Account type (gemini or antigravity)")
        .action(async (type) => {
        const normalized = type.trim().toLowerCase();
        if (normalized !== "gemini" && normalized !== "antigravity") {
            console.error("Invalid account type. Use gemini or antigravity.");
            process.exit(1);
        }
        const spinner = (0, ui_1.createSpinner)(`Adding ${normalized} account...`).start();
        try {
            let clientId;
            let clientSecret;
            if (normalized === "gemini") {
                clientId = process.env.GOOGLE_CLIENT_ID_GEMINI || "YOUR_GEMINI_CLIENT_ID";
                clientSecret = process.env.GOOGLE_CLIENT_SECRET_GEMINI || "YOUR_GEMINI_CLIENT_SECRET";
                const authService = new gemini_auth_1.GeminiAuthService(clientId, clientSecret, "https://accounts.google.com/o/oauth2/v2/auth", "https://oauth2.googleapis.com/token", "https://www.googleapis.com/oauth2/v1/userinfo", [
                    "https://www.googleapis.com/auth/cloud-platform",
                    "https://www.googleapis.com/auth/userinfo.email",
                    "https://www.googleapis.com/auth/userinfo.profile",
                ]);
                const success = await authService.connect();
                if (!success)
                    throw new Error("Failed to connect Gemini account");
                const account = {
                    id: crypto_1.default.randomUUID(),
                    type: "gemini",
                    email: "user@example.com",
                    accessToken: "placeholder-access-token",
                    refreshToken: "placeholder-refresh-token",
                    expiresIn: 3600,
                    scope: "https://www.googleapis.com/auth/cloud-platform",
                    projectId: "placeholder-project-id",
                    isActive: true,
                    isRateLimited: false,
                    quotaExhausted: false,
                    priority: accountManager.listAccounts().length + 1,
                    createdAt: new Date(),
                    updatedAt: new Date()
                };
                await accountManager.addAccount(account);
            }
            else {
                clientId = process.env.GOOGLE_CLIENT_ID_ANTIGRAVITY || "YOUR_ANTIGRAVITY_CLIENT_ID";
                clientSecret = process.env.GOOGLE_CLIENT_SECRET_ANTIGRAVITY || "YOUR_ANTIGRAVITY_CLIENT_SECRET";
                const authService = new antigravity_1.AntigravityService(clientId, clientSecret, "https://accounts.google.com/o/oauth2/v2/auth", "https://oauth2.googleapis.com/token", "https://www.googleapis.com/oauth2/v1/userinfo", [
                    "https://www.googleapis.com/auth/cloud-platform",
                    "https://www.googleapis.com/auth/userinfo.email",
                    "https://www.googleapis.com/auth/userinfo.profile",
                    "https://www.googleapis.com/auth/cclog",
                    "https://www.googleapis.com/auth/experimentsandconfigs",
                ], "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", "https://cloudcode-pa.googleapis.com/v1internal:onboardUser", "google-api-nodejs-client/9.15.1", "google-cloud-sdk vscode_cloudshelleditor/0.1", JSON.stringify({ ideType: 9, platform: 3, pluginType: 2 }));
                const success = await authService.connect();
                if (!success)
                    throw new Error("Failed to connect Antigravity account");
                const account = {
                    id: crypto_1.default.randomUUID(),
                    type: "antigravity",
                    email: "user@example.com",
                    accessToken: "placeholder-access-token",
                    refreshToken: "placeholder-refresh-token",
                    expiresIn: 3600,
                    scope: "https://www.googleapis.com/auth/cloud-platform",
                    projectId: "placeholder-project-id",
                    isActive: true,
                    isRateLimited: false,
                    quotaExhausted: false,
                    priority: accountManager.listAccounts().length + 1,
                    createdAt: new Date(),
                    updatedAt: new Date()
                };
                await accountManager.addAccount(account);
            }
            spinner.succeed(`Successfully added ${normalized} account`);
            console.log("\nYou can now use this account with the Frouter proxy.");
        }
        catch (error) {
            spinner.fail(`Failed to add account: ${error.message}`);
            process.exit(1);
        }
    });
    program
        .command("remove-account <id>")
        .description("Remove an account by ID")
        .action((id) => {
        const removed = accountManager.removeAccount(id);
        if (removed) {
            console.log(`Removed account ${id}`);
        }
        else {
            console.log(`Account ${id} not found`);
            process.exit(1);
        }
    });
    program
        .command("list-accounts")
        .description("List all accounts")
        .action(() => {
        const accounts = accountManager.listAccounts();
        if (accounts.length === 0) {
            console.log("No accounts found.");
            return;
        }
        console.log("\nAccounts:");
        console.log("-------------------");
        accounts.forEach((acc) => {
            const status = acc.isActive ? "active" : "inactive";
            const limits = acc.isRateLimited ? "rate-limited" : acc.quotaExhausted ? "quota-exhausted" : "ok";
            console.log(`ID: ${acc.id}`);
            console.log(`  Type: ${acc.type}`);
            console.log(`  Email: ${acc.email}`);
            console.log(`  Status: ${status} (${limits})`);
            console.log(`  Priority: ${acc.priority}`);
            console.log(`  Created: ${acc.createdAt.toLocaleString()}`);
            console.log();
        });
    });
    program
        .command("config")
        .description("Manage configuration")
        .argument("<action>", "Action to perform (set, get, list)")
        .argument("[key]", "Configuration key")
        .argument("[value]", "Configuration value (for set action)")
        .action((action, key, value) => {
        console.log(`Config ${action}: ${key} = ${value}`);
    });
    program
        .command("status")
        .description("Show Frouter status")
        .action(() => {
        const accounts = accountManager.listAccounts();
        const activeAccounts = accountManager.getActiveAccounts();
        console.log("\nFrouter Status");
        console.log("-------------------");
        console.log(`Accounts: ${accounts.length} total, ${activeAccounts.length} active`);
        console.log(`Token Budget: ${tokenBudget.getUsed()}/${tokenBudget.getTotal()} tokens used (${tokenBudget.getBudgetUsagePercent().toFixed(1)}%)`);
        console.log(`Compression Ratio: ${(tokenBudget.getCompressionRatio() * 100).toFixed(1)}%`);
        console.log(`Proxy Port: ${program.opts().port}`);
        console.log(`Proxy Host: ${program.opts().host}`);
        console.log();
    });
    program
        .command("start")
        .description("Start the Frouter proxy")
        .action(async () => {
        const opts = program.opts();
        const port = parseInt(opts.port, 10) || 20129;
        const host = opts.host || "0.0.0.0";
        const proxy = new openai_compat_1.OpenAICompatibleProxy(accountManager, port);
        try {
            await proxy.start();
            if (!opts.noBrowser) {
                const dashboardUrl = `http://localhost:${port}`;
                console.log(`Opening dashboard at ${dashboardUrl}`);
                try {
                    await (0, open_1.default)(dashboardUrl);
                }
                catch (err) {
                    console.log("Could not open browser automatically");
                }
            }
            console.log("\nPress Ctrl+C to stop the proxy");
            process.on("SIGINT", async () => {
                console.log("\nShutting down...");
                await proxy.stop();
                process.exit(0);
            });
        }
        catch (error) {
            console.error(`Failed to start proxy: ${error.message}`);
            process.exit(1);
        }
    });
    program
        .command("test-token-saver")
        .description("Test token saving features")
        .action(() => {
        console.log("\nTesting Token Saver Features");
        console.log("-------------------");
        const compressor = new compressor_1.TokenCompressor();
        const testCode = `
        function helloWorld() {
          console.log("Hello, World!");
          return 42;
        }

        function unusedFunction() {
          return true;
        }

        const result = helloWorld();
      `;
        const compressed = compressor.compressCode(testCode, "helloWorld");
        console.log(`Original tokens: ~${compressor.estimateTokens(testCode)}`);
        console.log(`Compressed tokens: ~${compressor.estimateTokens(compressed.compressed)}`);
        console.log(`Saved tokens: ${compressed.savedTokens}`);
        const scorer = new relevance_1.RelevanceScorer();
        const chunks = [
            "The quick brown fox jumps over the lazy dog",
            "Frouter is a Gemini proxy with token saving capabilities",
            "JavaScript is a popular programming language for web development"
        ];
        const context = "Gemini proxy token saving";
        const scored = scorer.filterByRelevance(chunks, context, 0.1);
        console.log(`\nRelevance scoring for "${context}":`);
        scored.forEach((item) => {
            console.log(`  Score: ${item.score.toFixed(2)} - "${item.chunk.substring(0, 50)}..."`);
        });
        const budget = new budget_1.TokenBudgetManager(1000);
        budget.useTokens(300);
        console.log(`\nBudget Status: ${budget.getUsed()}/${budget.getTotal()} tokens (${budget.getBudgetUsagePercent().toFixed(1)}%)`);
        console.log(`Remaining: ${budget.getRemaining()} tokens`);
    });
    return program;
}
//# sourceMappingURL=commands.js.map