<?php
/**
 * AI Integration Module
 * Gemini and DeepSeek API integration for case analysis
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/functions.php';

// ============================================
// API CONFIGURATION
// ============================================

define('AI_CACHE_DIR', __DIR__ . '/../tmp/ai_cache/');

// ============================================
// GEMINI API (Google)
// ============================================

/**
 * Call Gemini API
 * @param string $prompt
 * @param array $options
 * @return string|null
 */
function callGeminiAPI($prompt, $options = []) {
    if (!USE_AI || empty(GEMINI_API_KEY)) {
        return null;
    }
    
    // Check cache first
    $cacheKey = 'gemini_' . md5($prompt);
    $cached = getAICache($cacheKey);
    if ($cached !== null) {
        return $cached;
    }
    
    $url = GEMINI_API_URL . '?key=' . GEMINI_API_KEY;
    
    $data = [
        'contents' => [
            [
                'parts' => [
                    ['text' => $prompt]
                ]
            ]
        ],
        'generationConfig' => [
            'temperature' => $options['temperature'] ?? 0.7,
            'maxOutputTokens' => $options['max_tokens'] ?? 2048,
            'topP' => $options['top_p'] ?? 0.95,
            'topK' => $options['top_k'] ?? 40
        ]
    ];
    
    $response = httpPost($url, $data);
    
    if ($response && isset($response['candidates'][0]['content']['parts'][0]['text'])) {
        $result = $response['candidates'][0]['content']['parts'][0]['text'];
        setAICache($cacheKey, $result);
        return $result;
    }
    
    logMessage("Gemini API error: " . json_encode($response), 'error');
    return null;
}

// ============================================
// DEEPSEEK API
// ============================================

/**
 * Call DeepSeek API
 * @param string $prompt
 * @param array $options
 * @return string|null
 */
function callDeepSeekAPI($prompt, $options = []) {
    if (!USE_AI || empty(DEEPSEEK_API_KEY)) {
        return null;
    }
    
    // Check cache first
    $cacheKey = 'deepseek_' . md5($prompt);
    $cached = getAICache($cacheKey);
    if ($cached !== null) {
        return $cached;
    }
    
    $url = DEEPSEEK_API_URL;
    
    $data = [
        'model' => 'deepseek-chat',
        'messages' => [
            [
                'role' => 'system',
                'content' => 'You are an expert classical homeopath specializing in Kent\'s Repertory.'
            ],
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ],
        'temperature' => $options['temperature'] ?? 0.7,
        'max_tokens' => $options['max_tokens'] ?? 2048,
        'top_p' => $options['top_p'] ?? 0.95
    ];
    
    $headers = [
        'Authorization: Bearer ' . DEEPSEEK_API_KEY,
        'Content-Type: application/json'
    ];
    
    $response = httpPost($url, $data, $headers);
    
    if ($response && isset($response['choices'][0]['message']['content'])) {
        $result = $response['choices'][0]['message']['content'];
        setAICache($cacheKey, $result);
        return $result;
    }
    
    logMessage("DeepSeek API error: " . json_encode($response), 'error');
    return null;
}

// ============================================
// CASE ANALYSIS FUNCTIONS
// ============================================

/**
 * Analyze case with AI
 * @param array $caseData
 * @param string $remedyName (optional)
 * @return array
 */
function analyzeCaseWithAI($caseData, $remedyName = null) {
    $prompt = buildCaseAnalysisPrompt($caseData, $remedyName);
    
    // Try Gemini first, fallback to DeepSeek
    $analysis = callGeminiAPI($prompt);
    if (!$analysis) {
        $analysis = callDeepSeekAPI($prompt);
    }
    
    if ($analysis) {
        return [
            'success' => true,
            'analysis' => $analysis,
            'ai_used' => $analysis ? 'gemini' : 'deepseek'
        ];
    }
    
    return [
        'success' => false,
        'error' => 'AI analysis failed. Please check API keys.'
    ];
}

/**
 * Build prompt for case analysis
 * @param array $caseData
 * @param string $remedyName
 * @return string
 */
function buildCaseAnalysisPrompt($caseData, $remedyName = null) {
    $prompt = "You are an expert classical homeopath. ";
    
    if ($remedyName) {
        $prompt .= "Analyze the suitability of $remedyName for this patient case.\n\n";
    } else {
        $prompt .= "Suggest potential remedies for this patient case.\n\n";
    }
    
    // Add case details
    $prompt .= "=== PATIENT CASE ===\n";
    
    if (!empty($caseData['chief_complaint'])) {
        $prompt .= "Chief Complaint: " . $caseData['chief_complaint'] . "\n";
    }
    
    if (!empty($caseData['case_history'])) {
        $prompt .= "History: " . $caseData['case_history'] . "\n";
    }
    
    if (!empty($caseData['physical_generals'])) {
        $prompt .= "Physical Generals: " . $caseData['physical_generals'] . "\n";
    }
    
    if (!empty($caseData['mental_emotional'])) {
        $prompt .= "Mental/Emotional State: " . $caseData['mental_emotional'] . "\n";
    }
    
    if (!empty($caseData['modalities'])) {
        $prompt .= "Modalities: " . $caseData['modalities'] . "\n";
    }
    
    if (!empty($caseData['selected_rubrics'])) {
        $rubrics = json_decode($caseData['selected_rubrics'], true);
        if (!empty($rubrics)) {
            $prompt .= "Selected Rubrics: " . implode(", ", $rubrics) . "\n";
        }
    }
    
    // Instructions for AI
    $prompt .= "\n=== INSTRUCTIONS ===\n";
    
    if ($remedyName) {
        $prompt .= "1. Compare $remedyName's Materia Medica with this case\n";
        $prompt .= "2. List key symptoms that match $remedyName\n";
        $prompt .= "3. Identify any contradictions\n";
        $prompt .= "4. Provide recommendation with potency suggestion\n";
        $prompt .= "5. Note any modalities that support this prescription\n";
    } else {
        $prompt .= "1. List top 5 indicated remedies with reasoning\n";
        $prompt .= "2. For each remedy, explain key matching symptoms\n";
        $prompt .= "3. Suggest potential rubrics from Kent's Repertory\n";
        $prompt .= "4. Note important modalities\n";
    }
    
    return $prompt;
}

/**
 * Extract rubrics from case using AI
 * @param string $caseText
 * @return array
 */
function extractRubricsWithAI($caseText) {
    $prompt = "Extract potential Kent's Repertory rubrics from this case. Return as JSON array.\n\n";
    $prompt .= "Case: $caseText\n\n";
    $prompt .= "Format: [{\"rubric\": \"MIND - ANXIETY\", \"relevance\": \"high\", \"reason\": \"...\"}]\n";
    $prompt .= "Only include relevant rubrics from Kent's Repertory.";
    
    $response = callGeminiAPI($prompt);
    if (!$response) {
        $response = callDeepSeekAPI($prompt);
    }
    
    if ($response) {
        // Try to extract JSON from response
        preg_match('/\[.*\]/s', $response, $matches);
        if (!empty($matches)) {
            return json_decode($matches[0], true);
        }
    }
    
    return [];
}

/**
 * Get remedy suggestion from AI
 * @param array $symptoms
 * @param array $topRemedies (current repertorization results)
 * @return array
 */
function getRemedySuggestionAI($symptoms, $topRemedies = []) {
    $prompt = "Based on these symptoms, suggest the most appropriate homeopathic remedy:\n\n";
    $prompt .= "Symptoms: " . json_encode($symptoms) . "\n\n";
    
    if (!empty($topRemedies)) {
        $prompt .= "Current repertorization top remedies: " . implode(", ", $topRemedies) . "\n\n";
    }
    
    $prompt .= "Provide response in JSON format:\n";
    $prompt .= "{\"suggested_remedy\": \"remedy_name\", \"confidence\": \"high/medium/low\", ";
    $prompt .= "\"reasoning\": \"explanation\", \"potency\": \"suggested_potency\"}";
    
    $response = callGeminiAPI($prompt);
    if (!$response) {
        $response = callDeepSeekAPI($prompt);
    }
    
    if ($response) {
        preg_match('/\{.*\}/s', $response, $matches);
        if (!empty($matches)) {
            return json_decode($matches[0], true);
        }
    }
    
    return ['suggested_remedy' => null, 'confidence' => 'low', 'reasoning' => 'AI analysis failed'];
}

// ============================================
// MATERIA MEDICA AI
// ============================================

/**
 * Get remedy summary from AI
 * @param string $remedyName
 * @return string|null
 */
function getRemedySummaryAI($remedyName) {
    $cacheKey = 'remedy_summary_' . md5($remedyName);
    $cached = getAICache($cacheKey);
    if ($cached !== null) {
        return $cached;
    }
    
    $prompt = "Provide a concise clinical summary of the homeopathic remedy $remedyName including:\n";
    $prompt .= "1. Key mental/emotional symptoms\n";
    $prompt .= "2. Key physical generals\n";
    $prompt .= "3. Characteristic modalities (better/worse)\n";
    $prompt .= "4. Clinical indications\n";
    $prompt .= "Keep it under 500 words.";
    
    $summary = callGeminiAPI($prompt);
    if (!$summary) {
        $summary = callDeepSeekAPI($prompt);
    }
    
    if ($summary) {
        setAICache($cacheKey, $summary, 86400); // Cache for 24 hours
    }
    
    return $summary;
}

/**
 * Compare two remedies using AI
 * @param string $remedy1
 * @param string $remedy2
 * @return string|null
 */
function compareRemediesAI($remedy1, $remedy2) {
    $cacheKey = 'remedy_compare_' . md5($remedy1 . '_' . $remedy2);
    $cached = getAICache($cacheKey);
    if ($cached !== null) {
        return $cached;
    }
    
    $prompt = "Compare and contrast the homeopathic remedies $remedy1 and $remedy2.\n";
    $prompt .= "Include:\n";
    $prompt .= "1. Key similarities\n";
    $prompt .= "2. Key differences\n";
    $prompt .= "3. Clinical differentiation points\n";
    $prompt .= "4. When to choose one over the other";
    
    $comparison = callGeminiAPI($prompt);
    if (!$comparison) {
        $comparison = callDeepSeekAPI($prompt);
    }
    
    if ($comparison) {
        setAICache($cacheKey, $comparison, 604800); // Cache for 7 days
    }
    
    return $comparison;
}

// ============================================
// UTILITY FUNCTIONS
// ============================================

/**
 * HTTP POST request helper
 * @param string $url
 * @param array $data
 * @param array $headers
 * @return array|null
 */
function httpPost($url, $data, $headers = []) {
    $ch = curl_init($url);
    
    $defaultHeaders = ['Content-Type: application/json'];
    $allHeaders = array_merge($defaultHeaders, $headers);
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $allHeaders);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        logMessage("CURL Error: $error", 'error');
        return null;
    }
    
    if ($httpCode !== 200) {
        logMessage("HTTP Error $httpCode: $response", 'error');
        return null;
    }
    
    return json_decode($response, true);
}

/**
 * Get AI cache
 * @param string $key
 * @return mixed|null
 */
function getAICache($key) {
    if (!is_dir(AI_CACHE_DIR)) {
        mkdir(AI_CACHE_DIR, 0755, true);
    }
    
    $cacheFile = AI_CACHE_DIR . $key . '.json';
    
    if (!file_exists($cacheFile)) {
        return null;
    }
    
    $data = json_decode(file_get_contents($cacheFile), true);
    
    if ($data && $data['expiry'] > time()) {
        return $data['value'];
    }
    
    // Delete expired cache
    if (file_exists($cacheFile)) {
        unlink($cacheFile);
    }
    
    return null;
}

/**
 * Set AI cache
 * @param string $key
 * @param mixed $value
 * @param int $duration (seconds)
 * @return bool
 */
function setAICache($key, $value, $duration = 3600) {
    if (!is_dir(AI_CACHE_DIR)) {
        mkdir(AI_CACHE_DIR, 0755, true);
    }
    
    $cacheFile = AI_CACHE_DIR . $key . '.json';
    $data = [
        'value' => $value,
        'expiry' => time() + $duration,
        'created' => time()
    ];
    
    return file_put_contents($cacheFile, json_encode($data)) !== false;
}

/**
 * Clear AI cache
 * @param string $key (null for all)
 * @return bool
 */
function clearAICache($key = null) {
    if ($key === null) {
        $files = glob(AI_CACHE_DIR . '*.json');
        foreach ($files as $file) {
            unlink($file);
        }
        return true;
    }
    
    $cacheFile = AI_CACHE_DIR . $key . '.json';
    if (file_exists($cacheFile)) {
        return unlink($cacheFile);
    }
    
    return false;
}

/**
 * Check if AI is available
 * @return bool
 */
function isAIAvailable() {
    return USE_AI && (!empty(GEMINI_API_KEY) || !empty(DEEPSEEK_API_KEY));
}

/**
 * Get AI usage statistics
 * @return array
 */
function getAIStatistics() {
    $stats = [
        'cache_files' => 0,
        'cache_size' => 0,
        'last_cleanup' => null
    ];
    
    if (is_dir(AI_CACHE_DIR)) {
        $files = glob(AI_CACHE_DIR . '*.json');
        $stats['cache_files'] = count($files);
        
        $totalSize = 0;
        foreach ($files as $file) {
            $totalSize += filesize($file);
        }
        $stats['cache_size'] = formatFileSize($totalSize);
        
        // Check last cache file
        if (!empty($files)) {
            $latest = max(array_map('filemtime', $files));
            $stats['last_cleanup'] = date(DISPLAY_DATE_TIME_FORMAT, $latest);
        }
    }
    
    $stats['api_configured'] = [
        'gemini' => !empty(GEMINI_API_KEY),
        'deepseek' => !empty(DEEPSEEK_API_KEY)
    ];
    
    $stats['enabled'] = isAIAvailable();
    
    return $stats;
}