/**
 * CLI Auth Token Resolver
 *
 * Reads OAuth tokens from existing CLI tools so users can
 * piggyback on their Claude Code or Codex subscriptions.
 *
 * Supported CLIs:
 *   --provider claude-code  → reads ~/.claude/.credentials.json
 *   --provider codex        → reads ~/.codex/auth.json
 */
import fs from "node:fs";
import path from "node:path";
import { log } from "../utils/logger.js";
const HOME = process.env.HOME || process.env.USERPROFILE || ".";
/**
 * Try to resolve an API key from a CLI tool's auth storage.
 * Returns null if the provider doesn't match or auth files aren't found.
 */
export function resolveCliAuth(provider) {
    switch (provider) {
        case "claude-code":
            return resolveClaudeCode();
        case "codex":
            return resolveCodex();
        default:
            return null;
    }
}
function resolveClaudeCode() {
    const credPath = path.join(HOME, ".claude", ".credentials.json");
    if (!fs.existsSync(credPath)) {
        log.warn("Claude Code credentials not found. Run 'claude' to authenticate first.");
        return null;
    }
    try {
        const raw = fs.readFileSync(credPath, "utf-8");
        const creds = JSON.parse(raw);
        if (!creds.claudeAiOauth?.accessToken) {
            log.warn("Claude Code credentials found but no OAuth token. Re-authenticate with 'claude'.");
            return null;
        }
        const { accessToken, expiresAt, subscriptionType } = creds.claudeAiOauth;
        // Check expiry
        if (expiresAt && Date.now() > expiresAt) {
            log.warn("Claude Code OAuth token expired. Run 'claude' to refresh it.");
            return null;
        }
        // Warn if expiring soon (within 1 hour)
        if (expiresAt && Date.now() > expiresAt - 3600000) {
            const mins = Math.round((expiresAt - Date.now()) / 60000);
            log.warn(`Claude Code token expires in ${mins} minutes. Run 'claude' to refresh.`);
        }
        log.info(`Claude Code auth: ${subscriptionType || "unknown"} subscription`);
        return {
            apiKey: accessToken,
            baseUrl: "https://api.anthropic.com",
            provider: "claude-code",
        };
    }
    catch (err) {
        log.warn(`Failed to read Claude Code credentials: ${err instanceof Error ? err.message : String(err)}`);
        return null;
    }
}
function resolveCodex() {
    const authPath = path.join(HOME, ".codex", "auth.json");
    if (!fs.existsSync(authPath)) {
        log.warn("Codex CLI credentials not found. Run 'codex' to authenticate first.");
        return null;
    }
    try {
        const raw = fs.readFileSync(authPath, "utf-8");
        const creds = JSON.parse(raw);
        if (!creds.tokens?.access_token) {
            log.warn("Codex credentials found but no access token. Re-authenticate with 'codex'.");
            return null;
        }
        const { access_token } = creds.tokens;
        // JWT tokens have 3 parts — basic validation
        if (!access_token.includes(".")) {
            log.warn("Codex access token doesn't look like a valid JWT.");
            return null;
        }
        // Check JWT expiry (payload is base64url-encoded middle part)
        try {
            const payload = JSON.parse(Buffer.from(access_token.split(".")[1], "base64url").toString());
            if (payload.exp && Date.now() / 1000 > payload.exp) {
                log.warn("Codex OAuth token expired. Run 'codex' to refresh it.");
                return null;
            }
            if (payload.exp && Date.now() / 1000 > payload.exp - 3600) {
                const mins = Math.round((payload.exp - Date.now() / 1000) / 60);
                log.warn(`Codex token expires in ${mins} minutes. Run 'codex' to refresh.`);
            }
        }
        catch {
            // Can't parse JWT — proceed anyway
        }
        log.info("Codex CLI auth: using ChatGPT subscription");
        return {
            apiKey: access_token,
            baseUrl: "https://api.openai.com/v1",
            provider: "codex",
        };
    }
    catch (err) {
        log.warn(`Failed to read Codex credentials: ${err instanceof Error ? err.message : String(err)}`);
        return null;
    }
}
//# sourceMappingURL=cli-auth.js.map