import chalk from "chalk";
import { getActiveOrg, getAgentApiToken, listOrganizations, loadCredentials, refreshCredentials, resolveContext, } from "../internal/index.js";
function isLoopbackUrl(url) {
    try {
        const { hostname } = new URL(url);
        return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1");
    }
    catch {
        return false;
    }
}
export async function whoamiCommand(options) {
    const target = await resolveContext(options?.context);
    const creds = await refreshCredentials(await loadCredentials(target.name), target.name);
    if (options?.json) {
        await emitJson(target, creds);
        return;
    }
    if (!creds) {
        const envToken = process.env.LOBU_API_TOKEN;
        if (envToken) {
            console.log(chalk.dim("\n  Authenticated via LOBU_API_TOKEN environment variable."));
            console.log(chalk.dim(`  Context: ${target.name}`));
            console.log(chalk.dim(`  API URL: ${target.url}`));
            console.log(chalk.dim("  Lobu Cloud is in early access.\n"));
            return;
        }
        console.log(chalk.dim("\n  Not logged in."));
        console.log(chalk.dim(`  Context: ${target.name}`));
        console.log(chalk.dim(`  API URL: ${target.url}`));
        console.log(chalk.dim("  Run `lobu login` to authenticate.\n"));
        return;
    }
    console.log(chalk.bold("\n  Lobu CLI"));
    console.log(chalk.dim(`  Context: ${target.name}`));
    console.log(chalk.dim(`  API URL: ${target.url}`));
    if (creds.name) {
        console.log(chalk.dim(`  Name: ${creds.name}`));
    }
    if (creds.email) {
        console.log(chalk.dim(`  User: ${creds.email}`));
    }
    if (creds.userId) {
        console.log(chalk.dim(`  User ID: ${creds.userId}`));
    }
    console.log();
}
async function emitJson(target, creds) {
    const local = isLoopbackUrl(target.url);
    // For loopback contexts with no stored creds, getAgentApiToken transparently
    // POSTs /api/local-init to mint a worker PAT + session — the same zero-config
    // handshake the menu bar used to drive natively. This is what makes a fresh
    // `lobu run` install "just work" in the app without a manual login.
    let workerToken;
    try {
        workerToken = (await getAgentApiToken(target.name)) ?? undefined;
    }
    catch {
        workerToken = undefined;
    }
    // local-init may have written fresh creds (loopback bootstrap) — re-read so
    // identity/accessToken below reflect them.
    const effective = creds ?? (await loadCredentials(target.name));
    let organizations = [];
    try {
        organizations = (await listOrganizations({ context: target.name })).map((org) => ({ slug: org.slug, name: org.name }));
    }
    catch {
        organizations = [];
    }
    const orgSlug = (await getActiveOrg(target.name)) ?? organizations[0]?.slug;
    const result = {
        loggedIn: Boolean(effective?.accessToken || workerToken),
        context: target.name,
        apiUrl: target.url,
        local,
        email: effective?.email,
        name: effective?.name,
        userId: effective?.userId,
        accessToken: effective?.accessToken,
        workerToken: workerToken ?? effective?.accessToken,
        expiresAt: effective?.expiresAt,
        orgSlug,
        organizations,
    };
    process.stdout.write(`${JSON.stringify(result)}\n`);
}
//# sourceMappingURL=whoami.js.map