"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildClaudeCliAuthEnvironment = buildClaudeCliAuthEnvironment;
exports.buildClaudeEnvVarAuthEnvironment = buildClaudeEnvVarAuthEnvironment;
exports.getClaudeCliAuthStatus = getClaudeCliAuthStatus;
const command_1 = require("../core/command");
const CLAUDE_CONFIG_DIR_ENV_VAR = "CLAUDE_CONFIG_DIR";
const CLAUDE_CLI_AUTH_ENV_VARS = [
    "ANTHROPIC_API_KEY",
    "ANTHROPIC_AUTH_TOKEN",
    "CLAUDE_CODE_OAUTH_TOKEN",
];
const CLAUDE_ENV_VAR_AUTH_ENV_VARS = [
    CLAUDE_CONFIG_DIR_ENV_VAR,
    "ANTHROPIC_AUTH_TOKEN",
    "CLAUDE_CODE_OAUTH_TOKEN",
];
function buildClaudeCliAuthEnvironment(baseEnv, claudeConfigPath) {
    const env = {
        ...baseEnv,
    };
    env[CLAUDE_CONFIG_DIR_ENV_VAR] = claudeConfigPath;
    for (const envVarName of CLAUDE_CLI_AUTH_ENV_VARS) {
        delete env[envVarName];
    }
    return env;
}
function buildClaudeEnvVarAuthEnvironment(baseEnv, envVarName, value) {
    const env = {
        ...baseEnv,
        [envVarName]: value,
    };
    for (const envVarName of CLAUDE_ENV_VAR_AUTH_ENV_VARS) {
        delete env[envVarName];
    }
    return env;
}
async function getClaudeCliAuthStatus(input) {
    const run = input.run ?? command_1.runCommand;
    const result = await run({
        command: "claude",
        args: ["auth", "status", "--json"],
        env: buildClaudeCliAuthEnvironment(input.env ?? process.env, input.claudeConfigPath),
        allowNonZeroExit: true,
    });
    if (result.exitCode !== 0) {
        return null;
    }
    const parsed = JSON.parse(result.stdout);
    if (parsed === null ||
        typeof parsed !== "object" ||
        typeof parsed.loggedIn !== "boolean") {
        return null;
    }
    return {
        loggedIn: parsed.loggedIn,
    };
}
