"use strict";
/**
 * BFUI Adapter for Native AI Plugins
 *
 * This module provides BFUI-specific functionality using the Native AI plugin system.
 * It implements specialized methods for BFUI components such as document analysis,
 * RFP content generation, and other BFUI-specific AI tasks.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.BFUIAdapter = void 0;
exports.createBFUIAdapter = createBFUIAdapter;
const provider_adapter_js_1 = require("./provider-adapter.js");
const plugin_system_js_1 = require("./plugin-system.js");
/**
 * BFUI-specific adapter for Native AI plugins
 */
class BFUIAdapter {
    /**
     * Create a new BFUI adapter
     */
    constructor(providerIdOrAdapter) {
        if (providerIdOrAdapter instanceof provider_adapter_js_1.ProviderAdapter) {
            this.adapter = providerIdOrAdapter;
        }
        else if (typeof providerIdOrAdapter === 'string') {
            this.adapter = new provider_adapter_js_1.ProviderAdapter(providerIdOrAdapter);
        }
        else {
            // Use default provider
            const defaultProvider = plugin_system_js_1.pluginManager.getDefaultProvider();
            if (!defaultProvider) {
                throw new provider_adapter_js_1.ProviderAdapterError('No default provider available', 'no_default_provider', {});
            }
            this.adapter = new provider_adapter_js_1.ProviderAdapter(defaultProvider);
        }
    }
    /**
     * Analyze a document and extract key information
     */
    async analyzeDocument(document, options) {
        const detailed = options?.detailed || false;
        const categories = options?.categories || [];
        // Create system prompt based on options
        let systemPrompt = `Analyze the following document and provide: 
1. A concise summary (3-5 sentences)
2. Key points (5-7 bullet points)
3. Overall sentiment (positive, neutral, or negative)`;
        if (detailed) {
            systemPrompt += `\n4. Detailed analysis with supporting evidence`;
        }
        if (categories && categories.length > 0) {
            systemPrompt += `\n5. Categorization scores (0-100) for the following categories: ${categories.join(', ')}`;
        }
        // Create chat request
        const chatRequest = {
            model: 'claude-3-opus-20240229',
            provider: 'anthropic',
            messages: [
                {
                    role: 'user',
                    content: document
                }
            ],
            systemPrompt,
            temperature: 0.3,
            maxTokens: 2000
        };
        // Execute request
        const response = await this.adapter.chat(chatRequest);
        const content = response.choices[0]?.message.content || '';
        // Parse the response to extract structured information
        const result = this.parseDocumentAnalysis(content, categories);
        return result;
    }
    /**
     * Generate RFP content based on a document and requirements
     */
    async generateRFPContent(rfpDocument, requirements) {
        // Create system prompt
        const systemPrompt = `You are an expert in generating high-quality RFP (Request for Proposal) responses. 
Your task is to create compelling content that addresses the specific requirements provided.
Focus on:
1. Clear, concise language that directly addresses each requirement
2. Evidence-based claims that highlight capabilities
3. Specific, concrete examples that demonstrate expertise
4. Professional, business-appropriate tone
5. Logical organization with appropriate headings`;
        // Format requirements as a list
        const formattedRequirements = requirements.map((req, i) => `${i + 1}. ${req}`).join('\n');
        // Create user prompt
        const userPrompt = `Based on the following RFP document and requirements, generate a comprehensive response:

RFP DOCUMENT:
${rfpDocument}

REQUIREMENTS TO ADDRESS:
${formattedRequirements}

Please generate a well-structured RFP response that addresses each requirement with compelling content.`;
        // Create chat request
        const chatRequest = {
            model: 'claude-3-opus-20240229',
            provider: 'anthropic',
            messages: [
                {
                    role: 'user',
                    content: userPrompt
                }
            ],
            systemPrompt,
            temperature: 0.7,
            maxTokens: 4000
        };
        // Execute request
        const response = await this.adapter.chat(chatRequest);
        return response.choices[0]?.message.content || '';
    }
    /**
     * Parse document analysis response into structured format
     */
    parseDocumentAnalysis(content, categories) {
        // Default result
        const result = {
            summary: '',
            keyPoints: [],
            sentiment: 'neutral',
            categories: {}
        };
        // Extract summary (usually the first paragraph)
        const summaryMatch = content.match(/(?:summary:|summary)\s*([\s\S]+?)(?:\n\n|\n#|\n\*)/i);
        if (summaryMatch && summaryMatch[1]) {
            result.summary = summaryMatch[1].trim();
        }
        // Extract key points (usually bullet points)
        const keyPointsMatch = content.match(/(?:key points:|key points|main points:)([\s\S]+?)(?:\n\n|\n#|sentiment)/i);
        if (keyPointsMatch && keyPointsMatch[1]) {
            result.keyPoints = keyPointsMatch[1]
                .split(/\n+/)
                .map(point => point.replace(/^[•\-*]\s*/, '').trim())
                .filter(point => point.length > 0);
        }
        // Extract sentiment
        const sentimentMatch = content.match(/(?:sentiment:|sentiment)\s*(positive|neutral|negative)/i);
        if (sentimentMatch && sentimentMatch[1]) {
            const sentiment = sentimentMatch[1].toLowerCase();
            if (sentiment === 'positive' || sentiment === 'neutral' || sentiment === 'negative') {
                result.sentiment = sentiment;
            }
        }
        // Extract categories if requested
        if (categories.length > 0) {
            const categorySection = content.match(/(?:categories:|categorization:|category scores:)([\s\S]+?)(?:\n\n|\n#|$)/i);
            if (categorySection && categorySection[1]) {
                // Process each category
                categories.forEach(category => {
                    const categoryRegex = new RegExp(`${category}:?\\s*(\\d+)`, 'i');
                    const match = categorySection[1].match(categoryRegex);
                    if (match && match[1]) {
                        const score = parseInt(match[1], 10);
                        if (!isNaN(score)) {
                            if (!result.categories) {
                                result.categories = {};
                            }
                            result.categories[category] = score;
                        }
                    }
                });
            }
        }
        return result;
    }
    /**
     * Generate a compliance report for regulatory requirements
     */
    async generateComplianceReport(requirements, implementationDetails) {
        // Create system prompt
        const systemPrompt = `You are a compliance expert analyzing implementation details against regulatory requirements.
Your task is to determine compliance status, provide analysis, recommendations, and risk assessment.`;
        // Format requirements
        const formattedRequirements = requirements.map((req, i) => `${i + 1}. ${req}`).join('\n');
        // Create user prompt
        const userPrompt = `Analyze the following implementation details against these regulatory requirements:

REQUIREMENTS:
${formattedRequirements}

IMPLEMENTATION DETAILS:
${implementationDetails}

Provide a structured response with:
1. Overall compliance status (compliant, non_compliant, or partially_compliant)
2. Detailed analysis explaining your assessment
3. Recommendations for addressing any compliance gaps
4. Risk level assessment (low, medium, or high)`;
        // Create chat request
        const chatRequest = {
            model: 'claude-3-opus-20240229',
            provider: 'anthropic',
            messages: [
                {
                    role: 'user',
                    content: userPrompt
                }
            ],
            systemPrompt,
            temperature: 0.3,
            maxTokens: 3000
        };
        // Execute request
        const response = await this.adapter.chat(chatRequest);
        const content = response.choices[0]?.message.content || '';
        // Parse the response
        return this.parseComplianceReport(content);
    }
    /**
     * Parse compliance report from AI response
     */
    parseComplianceReport(content) {
        // Default result
        const result = {
            status: 'partially_compliant',
            analysis: '',
            recommendations: [],
            riskLevel: 'medium'
        };
        // Extract compliance status
        const statusMatch = content.match(/(?:compliance status:|status:)\s*(compliant|non_compliant|partially_compliant)/i);
        if (statusMatch && statusMatch[1]) {
            const status = statusMatch[1].toLowerCase();
            if (status === 'compliant' || status === 'non_compliant' || status === 'partially_compliant') {
                result.status = status;
            }
        }
        // Extract analysis
        const analysisMatch = content.match(/(?:analysis:|detailed analysis:)([\s\S]+?)(?:\n\n|\n#|recommendations:|$)/i);
        if (analysisMatch && analysisMatch[1]) {
            result.analysis = analysisMatch[1].trim();
        }
        // Extract recommendations
        const recommendationsMatch = content.match(/(?:recommendations:)([\s\S]+?)(?:\n\n|\n#|risk level:|$)/i);
        if (recommendationsMatch && recommendationsMatch[1]) {
            result.recommendations = recommendationsMatch[1]
                .split(/\n+/)
                .map(rec => rec.replace(/^[•\-*\d.]\s*/, '').trim())
                .filter(rec => rec.length > 0);
        }
        // Extract risk level
        const riskMatch = content.match(/(?:risk level:|risk assessment:)\s*(low|medium|high)/i);
        if (riskMatch && riskMatch[1]) {
            const risk = riskMatch[1].toLowerCase();
            if (risk === 'low' || risk === 'medium' || risk === 'high') {
                result.riskLevel = risk;
            }
        }
        return result;
    }
}
exports.BFUIAdapter = BFUIAdapter;
/**
 * Create a new BFUI adapter with the default provider
 */
function createBFUIAdapter(providerId) {
    return new BFUIAdapter(providerId);
}
//# sourceMappingURL=bfui-adapter.js.map