<?php
/**
 * ============================================================================
 * ResponseFormatter.php - Clean and Format AI Responses
 * ============================================================================
 * Handles HTML cleaning, markdown conversion, and response formatting
 */

namespace App;

class ResponseFormatter {
    
    /**
     * Clean HTML from database content and convert to markdown-style text
     */
    public static function cleanHtmlResponse($html) {
        if (empty($html)) {
            return '';
        }
        
        // Remove script and style tags completely
        $html = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $html);
        $html = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $html);
        
        // Convert headings to markdown
        $html = preg_replace('/<h1[^>]*>(.*?)<\/h1>/is', "\n\n**$1**\n\n", $html);
        $html = preg_replace('/<h2[^>]*>(.*?)<\/h2>/is', "\n\n**$1**\n\n", $html);
        $html = preg_replace('/<h3[^>]*>(.*?)<\/h3>/is', "\n**$1**\n", $html);
        $html = preg_replace('/<h4[^>]*>(.*?)<\/h4>/is', "\n**$1**\n", $html);
        $html = preg_replace('/<h5[^>]*>(.*?)<\/h5>/is', "\n**$1**\n", $html);
        $html = preg_replace('/<h6[^>]*>(.*?)<\/h6>/is', "**$1**\n", $html);
        
        // Convert strong/bold tags
        $html = preg_replace('/<(strong|b)[^>]*>(.*?)<\/(strong|b)>/is', '**$2**', $html);
        
        // Convert emphasis/italic tags
        $html = preg_replace('/<(em|i)[^>]*>(.*?)<\/(em|i)>/is', '*$2*', $html);
        
        // Convert lists
        $html = preg_replace('/<ul[^>]*>/is', "\n", $html);
        $html = preg_replace('/<\/ul>/is', "\n", $html);
        $html = preg_replace('/<ol[^>]*>/is', "\n", $html);
        $html = preg_replace('/<\/ol>/is', "\n", $html);
        $html = preg_replace('/<li[^>]*>(.*?)<\/li>/is', "- $1\n", $html);
        
        // Convert paragraphs
        $html = preg_replace('/<p[^>]*>(.*?)<\/p>/is', "$1\n\n", $html);
        
        // Convert line breaks
        $html = preg_replace('/<br\s*\/?>/i', "\n", $html);
        
        // Convert divs to line breaks
        $html = preg_replace('/<div[^>]*>/is', "\n", $html);
        $html = preg_replace('/<\/div>/is', "\n", $html);
        
        // Remove all other HTML tags
        $html = strip_tags($html);
        
        // Decode HTML entities
        $html = html_entity_decode($html, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        
        // Clean up whitespace
        $html = preg_replace('/\n{3,}/', "\n\n", $html); // Max 2 consecutive newlines
        $html = preg_replace('/[ \t]+/', ' ', $html); // Multiple spaces to single
        $html = trim($html);
        
        return $html;
    }
    
    /**
     * Format agricultural tips from database
     */
    public static function formatAgriculturalTip($tip) {
        if (empty($tip)) {
            return null;
        }
        
        $title = htmlspecialchars($tip['title'] ?? '');
        $content = self::cleanHtmlResponse($tip['content'] ?? '');
        $category = $tip['category'] ?? '';
        
        $response = "**{$title}**";
        
        if (!empty($category)) {
            $response .= " 🏷️ *{$category}*";
        }
        
        $response .= "\n\n{$content}";
        
        // Add source attribution
        $response .= "\n\n💡 *Source: AIMS Agricultural Knowledge Base*";
        
        return $response;
    }
    
    /**
     * Format crop disease information from database
     */
    public static function formatCropDisease($disease, $language = 'en') {
        if (empty($disease)) {
            return null;
        }
        
        $diseaseName = htmlspecialchars($disease['disease_name'] ?? '');
        $scientificName = $disease['scientific_name'] ?? '';
        $cropType = $disease['crop_type'] ?? '';
        $severity = $disease['severity_level'] ?? '';
        $symptoms = self::cleanHtmlResponse($disease['symptoms'] ?? '');
        $treatment = self::cleanHtmlResponse($disease['treatment'] ?? '');
        $prevention = self::cleanHtmlResponse($disease['prevention'] ?? '');
        
        $response = "**🦠 {$diseaseName}**\n";
        
        if ($scientificName) {
            $response .= "*{$scientificName}*\n";
        }
        
        $response .= "\n";
        
        if ($cropType) {
            $cropLabel = $language === 'en' ? 'Crop:' : 'Ekirime:';
            $response .= "**{$cropLabel}** " . ucfirst($cropType) . "\n";
        }
        
        if ($severity) {
            $severityLabel = $language === 'en' ? 'Severity:' : 'Obuzito:';
            $response .= "**{$severityLabel}** " . ucfirst($severity) . "\n";
        }
        
        if ($symptoms) {
            $symptomsLabel = $language === 'en' ? 'Symptoms:' : 'Obubonero:';
            $response .= "\n**{$symptomsLabel}**\n{$symptoms}\n";
        }
        
        if ($treatment) {
            $treatmentLabel = $language === 'en' ? 'Treatment:' : 'Okujjanjaba:';
            $response .= "\n**{$treatmentLabel}**\n{$treatment}\n";
        }
        
        if ($prevention) {
            $preventionLabel = $language === 'en' ? 'Prevention:' : 'Okuziyiza:';
            $response .= "\n**{$preventionLabel}**\n{$prevention}\n";
        }
        
        return trim($response);
    }
    
    /**
     * Format farming schedule from database
     */
    public static function formatFarmingSchedule($schedules, $language = 'en') {
        if (empty($schedules)) {
            return null;
        }
        
        $title = $language === 'en' ? 'Farming Schedule' : 'Oludda lw\'Okulima';
        $response = "**📅 {$title}**\n\n";
        
        foreach ($schedules as $schedule) {
            $scheduleTitle = htmlspecialchars($schedule['title'] ?? '');
            $cropType = $schedule['crop_type'] ?? '';
            $activityType = $schedule['activity_type'] ?? '';
            $timing = $schedule['timing'] ?? '';
            $description = self::cleanHtmlResponse($schedule['description'] ?? '');
            
            $response .= "**{$scheduleTitle}**\n";
            
            if ($cropType || $activityType) {
                $response .= "*" . ucfirst($cropType);
                if ($activityType) {
                    $response .= " - " . ucfirst(str_replace('_', ' ', $activityType));
                }
                $response .= "*\n";
            }
            
            if ($timing) {
                $response .= "⏰ {$timing}\n";
            }
            
            if ($description) {
                $response .= "{$description}\n";
            }
            
            $response .= "\n";
        }
        
        return trim($response);
    }
    
    /**
     * Format market prices
     */
    public static function formatMarketPrices($prices, $productType, $language = 'en') {
        if (empty($prices)) {
            return null;
        }
        
        $title = $language === 'en' 
            ? "Market Prices for " . ucfirst($productType)
            : "Emiwendo gy'e" . ucfirst($productType);
            
        $response = "**💰 {$title}**\n\n";
        
        foreach ($prices as $price) {
            $location = htmlspecialchars($price['market_location'] ?? '');
            $amount = number_format($price['price'] ?? 0, 0);
            $unit = htmlspecialchars($price['unit'] ?? 'kg');
            $date = date('M d, Y', strtotime($price['price_date'] ?? 'now'));
            
            $response .= "📍 **{$location}**\n";
            $response .= "   UGX {$amount} per {$unit}\n";
            $response .= "   *{$date}*\n\n";
        }
        
        // Add advice
        if ($language === 'en') {
            $response .= "\n💡 **Tips:**\n";
            $response .= "- Compare prices across markets\n";
            $response .= "- Set price alerts in AIMS\n";
            $response .= "- Consider transport costs\n";
            $response .= "- Join farmer groups for bulk selling\n";
        } else {
            $response .= "\n💡 **Amagezi:**\n";
            $response .= "- Geraageranya emiwendo mu bbabali\n";
            $response .= "- Teekawo alerts za miwendo mu AIMS\n";
            $response .= "- Lowooza ku musolo gw'entambula\n";
            $response .= "- Yingira mu bibiina by'abalimi okutunda bumu\n";
        }
        
        return $response;
    }
    
    /**
     * Extract clean text excerpt for previews
     */
    public static function getExcerpt($text, $maxLength = 100) {
        $text = self::cleanHtmlResponse($text);
        
        if (mb_strlen($text) <= $maxLength) {
            return $text;
        }
        
        $excerpt = mb_substr($text, 0, $maxLength);
        
        // Try to break at last word
        $lastSpace = mb_strrpos($excerpt, ' ');
        if ($lastSpace !== false && $lastSpace > $maxLength * 0.7) {
            $excerpt = mb_substr($excerpt, 0, $lastSpace);
        }
        
        return rtrim($excerpt, " \n\r\t.,;:!?") . '...';
    }
    
    /**
     * Add emojis based on content type
     */
    public static function addContextEmojis($text, $topic) {
        $emojiMap = [
            'disease' => '🦠',
            'pest' => '🐛',
            'price' => '💰',
            'weather' => '🌤️',
            'planting' => '🌱',
            'harvest' => '🌾',
            'livestock' => '🐔',
            'cattle' => '🐄',
            'goat' => '🐐',
            'pig' => '🐷',
            'fertilizer' => '💊',
            'water' => '💧',
            'soil' => '🌍',
        ];
        
        foreach ($emojiMap as $keyword => $emoji) {
            if (stripos($topic, $keyword) !== false) {
                return $emoji . ' ' . $text;
            }
        }
        
        return $text;
    }
    
    /**
     * Highlight important warnings or alerts
     */
    public static function highlightWarnings($text) {
        // Add warning emoji to critical phrases
        $warningPhrases = [
            'no cure' => '⚠️ NO CURE',
            'emergency' => '🚨 EMERGENCY',
            'urgent' => '⚠️ URGENT',
            'critical' => '⚠️ CRITICAL',
            'deadly' => '☠️ DEADLY',
            'dangerous' => '⚠️ DANGEROUS',
        ];
        
        foreach ($warningPhrases as $phrase => $replacement) {
            $text = preg_replace('/\b' . preg_quote($phrase, '/') . '\b/i', $replacement, $text);
        }
        
        return $text;
    }
    
    /**
     * Format response with proper spacing and structure
     */
    public static function finalFormat($text) {
        // Ensure sections are properly spaced
        $text = preg_replace('/\n{3,}/', "\n\n", $text);
        
        // Ensure bullets have proper spacing
        $text = preg_replace('/^- /m', "\n- ", $text);
        
        // Add highlight to key terms
        $text = self::highlightWarnings($text);
        
        return trim($text);
    }
}