import { getServiceUrls } from '@agentuity/config';
import { AIGatewayService } from '@agentuity/aigateway';
import { createServerFetchAdapter } from '@agentuity/server';
import * as tui from "../../../tui.js";
const defaultAIGatewayRegion = 'usc';
export function getAIGatewayUrl(region, overrides) {
    if (process.env.AGENTUITY_AIGATEWAY_URL) {
        return process.env.AGENTUITY_AIGATEWAY_URL;
    }
    if (overrides?.aigateway_url) {
        return overrides.aigateway_url;
    }
    return getServiceUrls(region || process.env.AGENTUITY_REGION || defaultAIGatewayRegion)
        .aigateway;
}
export function createAIGatewayService(ctx) {
    const orgId = ctx.project?.orgId ??
        ctx.options.orgId ??
        (process.env.AGENTUITY_CLOUD_ORG_ID || ctx.config?.preferences?.orgId);
    if (!orgId) {
        tui.fatal('Organization ID is required. Either run from a project directory or use --org-id flag.');
    }
    const adapter = createServerFetchAdapter({
        headers: {
            Authorization: `Bearer ${ctx.auth.apiKey}`,
            'x-agentuity-orgid': orgId,
        },
    }, ctx.logger);
    return new AIGatewayService(getAIGatewayUrl(ctx.region, ctx.config?.overrides), adapter);
}
export function createPublicAIGatewayService(ctx) {
    const adapter = createServerFetchAdapter({ headers: {} }, ctx.logger);
    return new AIGatewayService(getAIGatewayUrl(ctx.region, ctx.config?.overrides), adapter);
}
export function getCompletionText(response) {
    const choices = response.choices;
    const first = Array.isArray(choices) && choices.length > 0
        ? choices[0]
        : undefined;
    const content = first?.message?.content ?? first?.text ?? response.content;
    if (typeof content === 'string') {
        return content;
    }
    if (Array.isArray(content)) {
        return content
            .map((part) => {
            if (typeof part === 'string')
                return part;
            if (part && typeof part === 'object' && 'text' in part) {
                const text = part.text;
                return typeof text === 'string' ? text : '';
            }
            return '';
        })
            .join('');
    }
    return '';
}
//# sourceMappingURL=util.js.map