"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MicrosoftCopilotStudioProvider = void 0;
const logger_1 = __importDefault(require("../../logger"));
const DIRECT_LINE_BASE_URLS = {
    Global: 'https://directline.botframework.com/v3/directline',
    Europe: 'https://europe.directline.botframework.com/v3/directline',
    India: 'https://india.directline.botframework.com/v3/directline',
};
const FROM_ID = 'trusys-client';
const FROM_NAME = 'trusys';
const POLL_ATTEMPTS = 60;
const POLL_INTERVAL_MS = 1000;
async function fetchJson(url, options = {}) {
    const { headers: initHeaders = {}, body, method = body == null ? 'GET' : 'POST', signal } = options;
    const headers = { ...initHeaders };
    if (body !== undefined && body !== '') {
        headers['Content-Type'] = 'application/json';
    }
    const res = await fetch(url, {
        method,
        headers,
        body: body === undefined || body === '' ? undefined : body,
        signal,
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
        const message = data?.message || data?.error?.message || res.statusText || 'Request failed';
        const err = new Error(message);
        err.status = res.status;
        err.body = data;
        throw err;
    }
    return data;
}
class MicrosoftCopilotStudioProvider {
    constructor(config, options = {}) {
        this.config = options.config || {};
        this.providerConfig = config;
    }
    id() {
        return `microsoft-copilot-studio:${this.providerConfig.region}`;
    }
    getBaseUrl() {
        const region = this.providerConfig.region || 'Global';
        return DIRECT_LINE_BASE_URLS[region] || DIRECT_LINE_BASE_URLS.Global;
    }
    getSecret() {
        const secret = this.providerConfig.secret?.trim();
        if (!secret) {
            throw new Error('Microsoft Copilot Studio secret is required (Bot Framework > Settings > Security > Web channel).');
        }
        return secret;
    }
    async callApi(prompt, _context) {
        const baseUrl = this.getBaseUrl();
        try {
            const secret = this.getSecret();
            logger_1.default.debug(`[Microsoft Copilot Studio Provider]: Starting Direct Line conversation (${this.providerConfig.region})`);
            const startResponse = await fetchJson(`${baseUrl}/conversations`, {
                method: 'POST',
                headers: { Authorization: `Bearer ${secret}` },
                body: '',
            });
            const conversationId = startResponse?.conversationId;
            const token = startResponse?.token;
            if (!conversationId || !token) {
                throw new Error('Direct Line did not return conversationId or token');
            }
            await fetchJson(`${baseUrl}/conversations/${conversationId}/activities`, {
                method: 'POST',
                headers: { Authorization: `Bearer ${token}` },
                body: JSON.stringify({
                    type: 'message',
                    from: { id: FROM_ID, name: FROM_NAME },
                    text: prompt,
                }),
            });
            for (let i = 0; i < POLL_ATTEMPTS; i++) {
                await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
                const activityResponse = await fetchJson(`${baseUrl}/conversations/${conversationId}/activities`, {
                    method: 'GET',
                    headers: { Authorization: `Bearer ${token}` },
                });
                const activities = activityResponse?.activities ?? [];
                const agentReplies = activities.filter((a) => a?.from?.id !== FROM_ID);
                const lastReply = agentReplies[agentReplies.length - 1];
                if (lastReply?.text) {
                    return {
                        output: String(lastReply.text),
                        metadata: {
                            region: this.providerConfig.region,
                            conversationId,
                        },
                    };
                }
            }
            return {
                error: 'No agent response received within the polling window',
                output: '',
            };
        }
        catch (err) {
            const message = err?.body?.message ?? err?.body?.error?.message ?? err?.message ?? String(err);
            logger_1.default.error(`[Microsoft Copilot Studio Provider]: Error calling API: ${message}`);
            return {
                error: message,
                output: '',
            };
        }
    }
}
exports.MicrosoftCopilotStudioProvider = MicrosoftCopilotStudioProvider;
//# sourceMappingURL=microsoft-copilot-studio.js.map