"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAIProvider = void 0;
class OpenAIProvider {
    config;
    constructor(config) {
        this.config = config;
    }
    async analyzeMessage(message, history) {
        if (!this.config.apiKey) {
            return { confidence: 0, shouldEscalate: false };
        }
        try {
            const endpoint = this.config.endpoint ?? "https://api.openai.com/v1/chat/completions";
            const response = await fetch(endpoint, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${this.config.apiKey}`
                },
                body: JSON.stringify({
                    model: this.config.model ?? "gpt-3.5-turbo",
                    messages: [
                        {
                            role: "system",
                            content: "You are a support triage assistant. Analyze the user's message and respond with a JSON object containing: response (short helpful reply or null), confidence (0-1), suggestedCategory, suggestedPriority (LOW|NORMAL|HIGH|URGENT), sentiment (POSITIVE|NEUTRAL|NEGATIVE), urgency (LOW|MEDIUM|HIGH), shouldEscalate (boolean). Escalate if the user asks for a human, agent, or uses words like urgent/emergency/hacked/stolen/scam."
                        },
                        ...history.slice(-5).map((text) => ({ role: "user", content: text })),
                        { role: "user", content: message }
                    ],
                    temperature: 0.3,
                    max_tokens: 300
                })
            });
            if (!response.ok) {
                return { confidence: 0, shouldEscalate: false };
            }
            const data = (await response.json());
            const content = data.choices?.[0]?.message?.content;
            if (!content)
                return { confidence: 0, shouldEscalate: false };
            const parsed = this.safeJsonParse(content);
            const suggestedPriority = String(parsed.suggestedPriority ?? "");
            const sentiment = String(parsed.sentiment ?? "");
            const urgency = String(parsed.urgency ?? "");
            return {
                response: typeof parsed.response === "string" ? parsed.response : undefined,
                confidence: typeof parsed.confidence === "number" ? parsed.confidence : 0,
                suggestedCategory: typeof parsed.suggestedCategory === "string" ? parsed.suggestedCategory : undefined,
                suggestedPriority: ["LOW", "NORMAL", "HIGH", "URGENT"].includes(suggestedPriority)
                    ? suggestedPriority
                    : undefined,
                sentiment: ["POSITIVE", "NEUTRAL", "NEGATIVE"].includes(sentiment)
                    ? sentiment
                    : undefined,
                urgency: ["LOW", "MEDIUM", "HIGH"].includes(urgency) ? urgency : undefined,
                shouldEscalate: Boolean(parsed.shouldEscalate)
            };
        }
        catch {
            return { confidence: 0, shouldEscalate: false };
        }
    }
    async generateReply(message, history, context) {
        if (!this.config.apiKey)
            return undefined;
        try {
            const endpoint = this.config.endpoint ?? "https://api.openai.com/v1/chat/completions";
            const response = await fetch(endpoint, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${this.config.apiKey}`
                },
                body: JSON.stringify({
                    model: this.config.model ?? "gpt-3.5-turbo",
                    messages: [
                        {
                            role: "system",
                            content: `You are a helpful support assistant. ${context} Keep replies concise and friendly. If you cannot answer, say you will pass this to the team.`
                        },
                        ...history.slice(-5).map((text) => ({ role: "user", content: text })),
                        { role: "user", content: message }
                    ],
                    temperature: 0.5,
                    max_tokens: 400
                })
            });
            if (!response.ok)
                return undefined;
            const data = (await response.json());
            return data.choices?.[0]?.message?.content?.trim() || undefined;
        }
        catch {
            return undefined;
        }
    }
    safeJsonParse(content) {
        try {
            const cleaned = content.replace(/^```json\s*|\s*```$/g, "").trim();
            return JSON.parse(cleaned);
        }
        catch {
            return {};
        }
    }
}
exports.OpenAIProvider = OpenAIProvider;
