/**
 * AI Helper
 * AI-powered case analysis and remedy suggestions
 */

// ============================================
// AI Helper Class
// ============================================

class AIHelper {
    constructor() {
        this.apiEndpoint = 'api/ai-analyze.php';
        this.isAnalyzing = false;
        this.init();
    }
    
    init() {
        this.bindEvents();
    }
    
    bindEvents() {
        const analyzeBtn = document.getElementById('aiAnalyzeBtn');
        if (analyzeBtn) {
            analyzeBtn.addEventListener('click', () => this.analyzeCase());
        }
        
        const suggestBtn = document.getElementById('aiSuggestBtn');
        if (suggestBtn) {
            suggestBtn.addEventListener('click', () => this.suggestRemedy());
        }
        
        const extractBtn = document.getElementById('aiExtractBtn');
        if (extractBtn) {
            extractBtn.addEventListener('click', () => this.extractRubrics());
        }
    }
    
    async analyzeCase() {
        const caseText = this.getCaseText();
        if (!caseText) {
            this.showError('Please enter case details');
            return;
        }
        
        if (this.isAnalyzing) return;
        this.isAnalyzing = true;
        this.showLoading('Analyzing case with AI...');
        
        try {
            const response = await fetch('api/ai-analyze.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'analyze',
                    case_text: caseText
                })
            });
            const data = await response.json();
            
            if (data.success) {
                this.displayAnalysis(data.analysis);
                this.saveToHistory(data.analysis);
            } else {
                this.showError(data.error || 'Analysis failed');
            }
        } catch (error) {
            console.error('AI analysis error:', error);
            this.showError('Network error. Please try again.');
        } finally {
            this.isAnalyzing = false;
            this.hideLoading();
        }
    }
    
    async suggestRemedy() {
        const symptoms = this.getSymptomsText();
        if (!symptoms) {
            this.showError('Please enter symptoms');
            return;
        }
        
        if (this.isAnalyzing) return;
        this.isAnalyzing = true;
        this.showLoading('Getting remedy suggestions...');
        
        try {
            const response = await fetch('api/ai-suggest.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'suggest',
                    symptoms: symptoms
                })
            });
            const data = await response.json();
            
            if (data.success) {
                this.displaySuggestions(data.suggestions);
            } else {
                this.showError(data.error || 'Suggestion failed');
            }
        } catch (error) {
            console.error('AI suggestion error:', error);
            this.showError('Network error. Please try again.');
        } finally {
            this.isAnalyzing = false;
            this.hideLoading();
        }
    }
    
    async extractRubrics() {
        const caseText = this.getCaseText();
        if (!caseText) {
            this.showError('Please enter case text');
            return;
        }
        
        if (this.isAnalyzing) return;
        this.isAnalyzing = true;
        this.showLoading('Extracting rubrics...');
        
        try {
            const response = await fetch('api/ai-extract-rubrics.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'extract',
                    case_text: caseText
                })
            });
            const data = await response.json();
            
            if (data.success) {
                this.displayExtractedRubrics(data.rubrics);
            } else {
                this.showError(data.error || 'Extraction failed');
            }
        } catch (error) {
            console.error('AI extraction error:', error);
            this.showError('Network error. Please try again.');
        } finally {
            this.isAnalyzing = false;
            this.hideLoading();
        }
    }
    
    getCaseText() {
        const textarea = document.getElementById('caseText');
        return textarea ? textarea.value : '';
    }
    
    getSymptomsText() {
        const textarea = document.getElementById('symptomsText');
        return textarea ? textarea.value : '';
    }
    
    displayAnalysis(analysis) {
        const container = document.getElementById('aiAnalysisResult');
        if (container) {
            container.innerHTML = `
                <div class="ai-analysis-content">
                    <div class="alert alert-info">
                        <i class="fas fa-robot"></i> AI Analysis
                    </div>
                    <div class="analysis-text">${this.formatAnalysis(analysis)}</div>
                    <div class="mt-3">
                        <button class="btn btn-sm btn-secondary" onclick="window.aiHelper.copyToClipboard()">
                            <i class="fas fa-copy"></i> Copy to Clipboard
                        </button>
                    </div>
                </div>
            `;
        }
    }
    
    displaySuggestions(suggestions) {
        const container = document.getElementById('aiSuggestionsResult');
        if (container) {
            let html = '<div class="list-group">';
            suggestions.forEach(suggestion => {
                html += `
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-1">${suggestion.remedy}</h5>
                            <span class="badge bg-${suggestion.confidence === 'high' ? 'success' : (suggestion.confidence === 'medium' ? 'warning' : 'danger')}">
                                ${suggestion.confidence} confidence
                            </span>
                        </div>
                        <p class="mb-1">${suggestion.reasoning}</p>
                        <small>Suggested potency: ${suggestion.potency || '30C'}</small>
                        <div class="mt-2">
                            <button class="btn btn-sm btn-outline-primary" onclick="window.location.href='materia-medica/view.php?name=${encodeURIComponent(suggestion.remedy)}'">
                                View Materia Medica
                            </button>
                            <button class="btn btn-sm btn-success" onclick="window.location.href='cases/new.php?remedy=${encodeURIComponent(suggestion.remedy)}'">
                                Create Case
                            </button>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            container.innerHTML = html;
        }
    }
    
    displayExtractedRubrics(rubrics) {
        const container = document.getElementById('aiExtractedRubrics');
        if (container) {
            if (rubrics.length === 0) {
                container.innerHTML = '<div class="alert alert-info">No rubrics extracted</div>';
                return;
            }
            
            let html = '<div class="list-group">';
            rubrics.forEach(rubric => {
                html += `
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong>${rubric.full_path}</strong>
                                <span class="badge bg-${rubric.relevance === 'high' ? 'success' : (rubric.relevance === 'medium' ? 'warning' : 'danger')} ms-2">
                                    ${rubric.relevance}
                                </span>
                                ${rubric.reason ? `<div class="small text-muted mt-1">${rubric.reason}</div>` : ''}
                            </div>
                            <button class="btn btn-sm btn-primary" onclick="window.aiHelper.addRubricToCase(${rubric.id}, '${rubric.full_path}')">
                                Add to Case
                            </button>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            container.innerHTML = html;
        }
    }
    
    addRubricToCase(id, path) {
        if (window.repertorization) {
            window.repertorization.addRubric(id);
            this.showNotification(`Added: ${path}`, 'success');
        } else {
            window.location.href = `cases/new.php?rubric_id=${id}`;
        }
    }
    
    formatAnalysis(analysis) {
        // Convert markdown-like formatting to HTML
        return analysis
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            .replace(/\n/g, '<br>')
            .replace(/- (.*?)(<br>|$)/g, '<li>$1</li>');
    }
    
    copyToClipboard() {
        const content = document.querySelector('.analysis-text');
        if (content) {
            const text = content.innerText;
            navigator.clipboard.writeText(text).then(() => {
                this.showNotification('Copied to clipboard!', 'success');
            });
        }
    }
    
    showLoading(message) {
        const overlay = document.getElementById('aiLoadingOverlay') || this.createLoadingOverlay();
        overlay.querySelector('.loading-message').textContent = message;
        overlay.style.display = 'flex';
    }
    
    hideLoading() {
        const overlay = document.getElementById('aiLoadingOverlay');
        if (overlay) overlay.style.display = 'none';
    }
    
    createLoadingOverlay() {
        const overlay = document.createElement('div');
        overlay.id = 'aiLoadingOverlay';
        overlay.className = 'ai-loading-overlay';
        overlay.innerHTML = `
            <div class="loading-content">
                <div class="spinner-border text-primary"></div>
                <p class="loading-message mt-2">Processing...</p>
            </div>
        `;
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        `;
        document.body.appendChild(overlay);
        return overlay;
    }
    
    showError(message) {
        const container = document.getElementById('aiAnalysisResult');
        if (container) {
            container.innerHTML = `<div class="alert alert-danger">${message}</div>`;
        } else {
            alert(message);
        }
    }
    
    showNotification(message, type) {
        if (typeof showNotification === 'function') {
            showNotification(message, type);
        } else {
            alert(message);
        }
    }
    
    saveToHistory(analysis) {
        // Save to localStorage for history
        const history = JSON.parse(localStorage.getItem('ai_analysis_history') || '[]');
        history.unshift({
            timestamp: new Date().toISOString(),
            analysis: analysis.substring(0, 200)
        });
        localStorage.setItem('ai_analysis_history', JSON.stringify(history.slice(0, 20)));
    }
}

// Initialize AI Helper
let aiHelper = null;

document.addEventListener('DOMContentLoaded', () => {
    if (document.getElementById('aiAnalyzeBtn') || 
        document.getElementById('aiSuggestBtn') || 
        document.getElementById('aiExtractBtn')) {
        aiHelper = new AIHelper();
        window.aiHelper = aiHelper;
    }
});