"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAnthropicHandler = createAnthropicHandler;
// Anthropic does not expose a standard OAuth2 authorization server.
// Instead, users provide a credential via the Long Tail dashboard:
//
//   - OAuth token (sk-ant-oat01-...) from `claude setup-token`
//     -> Uses their Claude subscription (Pro/Max/Teams) at flat rate
//     -> Passed to subprocess as CLAUDE_CODE_OAUTH_TOKEN
//
//   - API key (sk-ant-api03-...) from console.anthropic.com
//     -> Billed per-token against their API account
//     -> Passed to subprocess as ANTHROPIC_API_KEY
//
// Flow:
//   1. createAuthorizationURL -> redirects to /connect/anthropic (dashboard form)
//   2. User pastes credential -> form redirects to callback with it as "code"
//   3. validateAuthorizationCode -> validates against Anthropic API
//   4. fetchUserInfo -> derives identity from the credential
//   5. Credential stored encrypted as access_token in lt_oauth_tokens
function createAnthropicHandler(cfg) {
    const handler = {
        config: { ...cfg, displayName: cfg.displayName || 'Anthropic' },
        createAuthorizationURL(state, _codeVerifier) {
            const baseUrl = handler.config.redirectUri?.replace(`/api/auth/oauth/anthropic/callback`, '') || '';
            const url = new URL(`${baseUrl}/connect/anthropic`);
            url.searchParams.set('state', state);
            return url;
        },
        async validateAuthorizationCode(credential, _codeVerifier) {
            const isOAuthToken = credential.startsWith('sk-ant-oat');
            // Validate the credential by calling the Anthropic API.
            // OAuth tokens use Authorization: Bearer; API keys use x-api-key.
            const headers = {
                'anthropic-version': '2023-06-01',
            };
            if (isOAuthToken) {
                headers['Authorization'] = `Bearer ${credential}`;
            }
            else {
                headers['x-api-key'] = credential;
            }
            const res = await fetch('https://api.anthropic.com/v1/models', { headers });
            if (!res.ok) {
                const body = await res.text().catch(() => '');
                const kind = isOAuthToken ? 'OAuth token' : 'API key';
                throw new Error(`Invalid Anthropic ${kind}: ${res.status} ${body}`);
            }
            return {
                accessToken: credential,
                refreshToken: null,
                accessTokenExpiresAt: null,
            };
        },
        async refreshAccessToken(_refreshToken) {
            throw new Error('Anthropic credentials do not support refresh');
        },
        async fetchUserInfo(credential) {
            const { createHash } = await Promise.resolve().then(() => __importStar(require('crypto')));
            const keyHash = createHash('sha256').update(credential).digest('hex').slice(0, 16);
            const isOAuthToken = credential.startsWith('sk-ant-oat');
            const prefix = credential.slice(0, 14);
            return {
                provider: 'anthropic',
                providerUserId: `anthropic-${keyHash}`,
                email: null,
                displayName: isOAuthToken
                    ? `Claude Subscription (${prefix}...)`
                    : `Anthropic API Key (${prefix}...)`,
                raw: {
                    credential_type: isOAuthToken ? 'oauth_token' : 'api_key',
                    prefix,
                },
            };
        },
    };
    return handler;
}
