import { spinner } from "toolcraft-design";
import { createExecutionResources, resolveCommandFlags } from "./shared.js";
import { executeLogin } from "./login.js";
import { executeLogout } from "./logout.js";
import { fetchPoeAuthIdentity } from "../../sdk/credentials.js";
export function registerAuthCommand(program, container) {
    const auth = program
        .command("auth")
        .description("Authentication and account commands.")
        .action(async () => {
        await executeStatus(program, container);
    });
    auth
        .command("status")
        .description("Show login status.")
        .action(async () => {
        await executeStatus(program, container);
    });
    auth
        .command("api-key")
        .description("Display stored API key.")
        .action(async () => {
        await executeApiKey(program, container);
    });
    auth
        .command("api_key", { hidden: true })
        .action(async () => {
        await executeApiKey(program, container);
    });
    auth
        .command("whoami")
        .description("Print Poe account identity as JSON (uses POE_API_KEY if set).")
        .action(async () => {
        await executeWhoami(program, container);
    });
    auth
        .command("login")
        .description("Store a Poe API key for reuse across commands.")
        .option("--api-key <key>", "Poe API key")
        .action(async (options) => {
        await executeLogin(program, container, options);
    });
    auth
        .command("logout")
        .description("Remove all configuration and credentials.")
        .action(async () => {
        await executeLogout(program, container);
    });
}
async function executeStatus(program, container) {
    const flags = resolveCommandFlags(program);
    const resources = createExecutionResources(container, flags, "auth:status");
    resources.logger.intro("auth status");
    try {
        const apiKey = await resolveAuthCredential(container, { readOnly: flags.dryRun });
        if (!apiKey) {
            resources.logger.info("Not logged in");
            resources.context.finalize();
            return;
        }
        if (flags.dryRun) {
            resources.logger.dryRun("Dry run: would fetch identity from Poe API.");
            resources.context.finalize();
            return;
        }
        const s = spinner();
        s.start("Checking authentication...");
        let identity;
        try {
            identity = await fetchPoeAuthIdentity({
                apiKey,
                baseUrl: container.env.poeApiBaseUrl,
                httpClient: container.httpClient
            });
        }
        catch (error) {
            s.stop("Authentication failed");
            throw error;
        }
        s.stop(`Logged in as ${identity.name} (@${identity.handle})`);
        resources.context.finalize();
    }
    catch (error) {
        if (error instanceof Error) {
            resources.logger.logException(error, "auth status", {
                operation: "auth-status"
            });
        }
        throw error;
    }
}
async function executeApiKey(program, container) {
    const flags = resolveCommandFlags(program);
    const apiKey = await container.readApiKey({ readOnly: flags.dryRun });
    if (!apiKey) {
        process.exitCode = 1;
        return;
    }
    process.stdout.write(apiKey);
}
async function resolveAuthCredential(container, options = {}) {
    const envKey = container.env.getVariable("POE_API_KEY");
    if (typeof envKey === "string" && envKey.trim().length > 0) {
        return envKey.trim();
    }
    return container.readApiKey(options);
}
async function executeWhoami(program, container) {
    const flags = resolveCommandFlags(program);
    const apiKey = await resolveAuthCredential(container, { readOnly: flags.dryRun });
    if (!apiKey) {
        process.exitCode = 1;
        return;
    }
    if (flags.dryRun) {
        const resources = createExecutionResources(container, flags, "auth:whoami");
        resources.logger.dryRun("Dry run: would fetch identity from Poe API.");
        resources.context.finalize();
        return;
    }
    const identity = await fetchPoeAuthIdentity({
        apiKey,
        baseUrl: container.env.poeApiBaseUrl,
        httpClient: container.httpClient
    });
    process.stdout.write(`${JSON.stringify(identity)}\n`);
}
//# sourceMappingURL=auth.js.map