#!/usr/bin/env python3
"""
🤖 Enhanced AI Shopping Schema Generator - Intelectra
Erzeugt KI-optimierte JSON-LD Schemas mit dynamischer Problem-DB-Abfrage

SICHER: Läuft komplett isoliert, keine Live-Shop Auswirkungen!
"""

import json
import sys
import re
import mysql.connector
from datetime import datetime
import os
from config import DB_CONFIG, ENABLE_FALLBACK, BASE_URL, SAFETY_ICON_BASE, LOG_DIR, SCHEMA_SAVE_DIR

class EnhancedAISchemaGenerator:
    def __init__(self):
        self.base_url = BASE_URL
        self.safety_icon_base = SAFETY_ICON_BASE
        self.db_connection = None
        
        # DB-Verbindung herstellen (sichere Fallback-Behandlung)
        if ENABLE_FALLBACK:
            try:
                self.connect_to_database()
            except Exception as e:
                self.log_error(f"DB connection failed: {str(e)} - Using fallback mode")
    
    def connect_to_database(self):
        """Sichere DB-Verbindung mit Config-basierter Konfiguration"""
        try:
            self.db_connection = mysql.connector.connect(**DB_CONFIG)
        except mysql.connector.Error as err:
            self.log_error(f"MySQL connection error: {err}")
            self.db_connection = None
    
    def generate_schema(self, item_data):
        """Erzeugt KI-optimiertes Schema für einen Artikel"""
        try:
            schema = {
                "@context": "https://schema.org",
                "@type": "Product",
                "name": item_data.get('name', ''),
                "identifier": f"intelectra-{item_data.get('item_id', '')}",
                "category": "Elektro-Ersatzteil",
                "url": f"{self.base_url}/artikel/{item_data.get('item_id', '')}",
                
                # Timestamp für Monitoring
                "_meta": {
                    "generated": datetime.now().isoformat(),
                    "generator": "Enhanced AI Schema v2.0 - Database Powered",
                    "source": "intelectra_live_shop",
                    "database_enabled": self.db_connection is not None
                }
            }
            
            # Sicherheitshinweise hinzufügen (wenn vorhanden)
            if item_data.get('warnings'):
                schema["safetyConsiderations"] = self.build_safety_schema(item_data['warnings'])
            
            # 🚀 NEUE DATABASE-POWERED Problem-Solution-Mapping!
            schema["solves"] = self.build_dynamic_problem_solutions(item_data)
            
            # Kompatibilitäts-Informationen
            if item_data.get('attributes'):
                schema["compatibleWith"] = self.build_compatibility_schema(item_data['attributes'])
            
            # Installations-Hinweise
            schema["installationHints"] = self.generate_installation_hints(item_data)
            
            return schema
            
        except Exception as e:
            self.log_error(f"Schema generation failed: {str(e)}")
            return None
    
    def build_dynamic_problem_solutions(self, item_data):
        """🚀 NEUE DATABASE-POWERED Problem-Solution Engine"""
        if not self.db_connection:
            # Fallback auf alte hardcoded Methode
            return self.build_fallback_problem_solutions(item_data)
        
        try:
            problems = self.get_problems_for_item(item_data)
            solutions = []
            
            for problem in problems:
                solution = {
                    "@type": "ProblemSolution",
                    "problem": problem['problem_title'],
                    "description": problem['problem_description'],
                    "symptoms": json.loads(problem['symptoms']),
                    "errorCodes": json.loads(problem['error_codes'] or '[]'),
                    "urgencyLevel": problem['urgency_level'],
                    "repairComplexity": problem['repair_complexity'],
                    "estimatedTime": f"{problem['installation_time_min']}-{problem['installation_time_max']} Minuten",
                    "toolsRequired": json.loads(problem['tools_needed'] or '[]'),
                    "safetyInstructions": problem['safety_notes'],
                    "difficultyLevel": problem['difficulty_description'],
                    "problemKeywords": json.loads(problem['keywords']),
                    "frequencyScore": problem['frequency_score'],  # Für KI-Ranking
                    "dataSource": "dynamic_database"
                }
                solutions.append(solution)
            
            return solutions
            
        except Exception as e:
            self.log_error(f"Database problem query failed: {str(e)}")
            return self.build_fallback_problem_solutions(item_data)
    
    def get_problems_for_item(self, item_data):
        """Intelligente Problem-Zuordnung basierend auf Item-Daten"""
        if not self.db_connection:
            return []
        
        try:
            cursor = self.db_connection.cursor(dictionary=True)
            
            # 1. Kategorie-Erkennung
            category = self.detect_category(item_data['name'], item_data.get('attributes', {}))
            
            # 2. Keyword-Matching
            item_keywords = self.extract_keywords(item_data['name'])
            
            # 3. DB-Abfrage mit Ranking
            query = """
                SELECT ps.*, 
                       COALESCE(SUM(pk.weight), 0) as relevance_score
                FROM problem_solutions ps
                LEFT JOIN problem_keywords pk ON ps.id = pk.problem_id
                WHERE (ps.problem_category = %s 
                   OR JSON_OVERLAPS(ps.keywords, %s)
                   OR pk.keyword IN ({placeholders}))
                   AND ps.active = TRUE
                GROUP BY ps.id
                ORDER BY relevance_score DESC, ps.frequency_score DESC
                LIMIT 5
            """.format(placeholders=','.join(['%s'] * len(item_keywords)))
            
            params = [category, json.dumps(item_keywords)] + item_keywords
            cursor.execute(query, params)
            problems = cursor.fetchall()
            
            cursor.close()
            return problems
            
        except Exception as e:
            self.log_error(f"Database query error: {str(e)}")
            return []
    
    def detect_category(self, item_name, attributes):
        """Intelligente Kategorie-Erkennung"""
        name_lower = item_name.lower()
        
        category_patterns = {
            'heating': ['heizstab', 'thermostat', 'ntc', 'temperaturfühler', 'heizung'],
            'pumping': ['pumpe', 'pump', 'ablaufpumpe', 'laugenpumpe', 'umwälzpumpe'],
            'motor_drive': ['motor', 'antrieb', 'antriebsmotor'],
            'door_system': ['türschloss', 'türgriff', 'türdichtung', 'door'],
            'electronics': ['platine', 'steuerung', 'elektronik', 'display', 'timer'],
            'mechanical': ['stoßdämpfer', 'feder', 'lager', 'riemen'],
            'water_system': ['schlauch', 'ventil', 'aquastop', 'wasserzulauf'],
            'filters': ['filter', 'sieb', 'flusensieb'],
            'lighting': ['lampe', 'led', 'birne', 'leuchte']
        }
        
        for category, keywords in category_patterns.items():
            if any(keyword in name_lower for keyword in keywords):
                return category
        
        return 'mechanical'  # Default
    
    def extract_keywords(self, item_name):
        """Extrahiert relevante Keywords aus Item-Name"""
        name_lower = item_name.lower()
        
        # Basis-Keywords extrahieren
        keywords = []
        
        # Wichtige Einzelwörter
        important_words = ['pumpe', 'motor', 'heizstab', 'schlauch', 'filter', 
                          'türschloss', 'dichtung', 'thermostat', 'sensor']
        
        for word in important_words:
            if word in name_lower:
                keywords.append(word)
        
        # Synonyme und Variationen
        if 'pump' in name_lower:
            keywords.extend(['pumpe', 'pump'])
        if 'heating' in name_lower:
            keywords.extend(['heizstab', 'heizung'])
        if 'door' in name_lower:
            keywords.extend(['tür', 'türschloss'])
            
        return list(set(keywords))
    
    def build_fallback_problem_solutions(self, item_data):
        """Fallback auf alte hardcoded Methode wenn DB nicht verfügbar"""
        name = item_data.get('name', '').lower()
        solutions = []
        
        # Vereinfachte Fallback-Logic (nur Top-Probleme)
        if any(word in name for word in ['pumpe', 'pump']):
            solutions.append({
                "@type": "ProblemSolution",
                "problem": "Wasser läuft nicht ab / Pumpe defekt",
                "symptoms": ["Gerät pumpt nicht", "Wasser steht", "E20 Fehler"],
                "urgencyLevel": "HIGH",
                "repairComplexity": "MEDIUM",
                "dataSource": "fallback_hardcoded"
            })
        
        if any(word in name for word in ['heizstab', 'heizung']):
            solutions.append({
                "@type": "ProblemSolution", 
                "problem": "Gerät heizt nicht",
                "symptoms": ["Kein warmes Wasser", "E15 Fehler"],
                "urgencyLevel": "HIGH",
                "repairComplexity": "MEDIUM",
                "dataSource": "fallback_hardcoded"
            })
        
        return solutions
    
    def build_safety_schema(self, warnings):
        """Konvertiert Sicherheitshinweise in KI-optimiertes Format"""
        safety_considerations = []
        
        for warning in warnings:
            consideration = {
                "@type": "SafetyConsideration",
                "name": warning.get('name', ''),
                "description": warning.get('beschreibung', ''),
                "warningLevel": self.detect_warning_level(warning.get('name', '')),
                "iconPath": f"{self.safety_icon_base}{warning.get('final_bilddateiname', '')}"
            }
            
            # Intelligente Kategorisierung
            if "elektrisch" in warning.get('name', '').lower():
                consideration["category"] = "electrical_hazard"
                consideration["preventiveMeasures"] = ["Netzstecker ziehen", "Spannungsfreiheit prüfen"]
            elif "quetsch" in warning.get('name', '').lower():
                consideration["category"] = "mechanical_hazard"
                consideration["preventiveMeasures"] = ["Schutzhandschuhe tragen", "Vorsichtig arbeiten"]
            
            safety_considerations.append(consideration)
        
        return safety_considerations
    
    def build_compatibility_schema(self, attributes):
        """Extrahiert Kompatibilitäts-Informationen aus Attributen"""
        compatible_brands = []
        
        # Pattern für bekannte Marken
        brand_patterns = {
            'siemens': ['siemens', 'bosch', 'neff', 'gaggenau'],
            'miele': ['miele'],
            'amica': ['amica', 'whirlpool', 'bauknecht', 'privileg'],
            'liebherr': ['liebherr']
        }
        
        # Suche nach Marken in Attributen
        for attr_key, attr_value in attributes.items():
            if isinstance(attr_value, str):
                for brand_group, brands in brand_patterns.items():
                    if any(brand in attr_value.lower() for brand in brands):
                        compatible_brands.extend(brands)
        
        return {
            "brands": list(set(compatible_brands)),
            "applianceTypes": self.detect_appliance_types(attributes)
        }
    
    def detect_appliance_types(self, attributes):
        """Erkennt Gerätetypen aus Attributen"""
        types = []
        
        type_keywords = {
            "Waschmaschine": ["waschmaschine", "washing", "wäsche"],
            "Geschirrspüler": ["geschirrspüler", "dishwasher", "spülmaschine"],
            "Kühlschrank": ["kühlschrank", "refrigerator", "kühl"],
            "Backofen": ["backofen", "oven", "herd"]
        }
        
        for attr_value in attributes.values():
            if isinstance(attr_value, str):
                for appliance, keywords in type_keywords.items():
                    if any(keyword in attr_value.lower() for keyword in keywords):
                        types.append(appliance)
        
        return list(set(types))
    
    def generate_installation_hints(self, item_data):
        """Generiert intelligente Installations-Hinweise"""
        name = item_data.get('name', '').lower()
        
        if 'schlauch' in name:
            return {
                "difficulty": "Einfach - ohne Fachmann machbar",
                "timeRequired": "5-10 Minuten",
                "toolsNeeded": ["Zange", "Schraubendreher"],
                "safetyNote": "Wasser abstellen vor Montage"
            }
        elif 'pumpe' in name:
            return {
                "difficulty": "Mittel - handwerkliches Geschick nötig",
                "timeRequired": "30-45 Minuten", 
                "toolsNeeded": ["Schraubendreher", "Zange", "Multimeter"],
                "safetyNote": "Strom abstellen! Gerät vom Netz trennen"
            }
        elif 'heizstab' in name:
            return {
                "difficulty": "Schwer - Fachmann empfohlen",
                "timeRequired": "60-90 Minuten",
                "toolsNeeded": ["Multimeter", "Spezialwerkzeug"],
                "safetyNote": "⚠️ HOCHSPANNUNG! Strom komplett abschalten"
            }
        
        return {
            "difficulty": "Mittlere Schwierigkeit",
            "timeRequired": "15-30 Minuten",
            "safetyNote": "Sicherheitshinweise beachten"
        }
    
    def detect_warning_level(self, warning_name):
        """Intelligente Warnstufen-Erkennung"""
        name_lower = warning_name.lower()
        
        if any(word in name_lower for word in ['elektrisch', 'strom', 'spannung']):
            return "CRITICAL"
        elif any(word in name_lower for word in ['heiß', 'temperatur', 'verbrennung']):
            return "HIGH"
        elif any(word in name_lower for word in ['quetsch', 'verletzung']):
            return "MEDIUM"
        else:
            return "LOW"
    
    def save_schema(self, schema, item_id):
        """Speichert Schema für späteren Abruf (optional)"""
        try:
            schema_file = f"{SCHEMA_SAVE_DIR}/enhanced_schema_{item_id}.json"
            
            os.makedirs(SCHEMA_SAVE_DIR, exist_ok=True)
            
            with open(schema_file, 'w', encoding='utf-8') as f:
                json.dump(schema, f, indent=2, ensure_ascii=False)
                
            return True
        except Exception as e:
            self.log_error(f"Schema save failed: {str(e)}")
            return False
    
    def log_error(self, message):
        """Fehler-Logging"""
        try:
            log_file = f"{LOG_DIR}/enhanced_ai_schema.log"
            timestamp = datetime.now().isoformat()
            
            os.makedirs(LOG_DIR, exist_ok=True)
            
            with open(log_file, 'a', encoding='utf-8') as f:
                f.write(f"{timestamp} ERROR: {message}\n")
        except:
            pass  # Silent fail für Live-Shop
    
    def __del__(self):
        """DB-Verbindung sauber schließen"""
        if self.db_connection:
            try:
                self.db_connection.close()
            except:
                pass

def main():
    """Hauptfunktion - wird von PHP aufgerufen"""
    if len(sys.argv) < 2:
        print(json.dumps({"error": "No input data provided"}))
        sys.exit(1)
    
    try:
        # Input von PHP parsen
        input_data = json.loads(sys.argv[1])
        
        # Enhanced Schema Generator initialisieren
        generator = EnhancedAISchemaGenerator()
        
        # Schema erzeugen
        schema = generator.generate_schema(input_data)
        
        if schema:
            # Optional: Schema speichern
            generator.save_schema(schema, input_data.get('item_id', 'unknown'))
            
            # Erfolg zurückgeben
            result = {
                "success": True,
                "schema_generated": True,
                "item_id": input_data.get('item_id'),
                "timestamp": datetime.now().isoformat(),
                "database_powered": generator.db_connection is not None,
                "problems_found": len(schema.get("solves", []))
            }
        else:
            result = {"success": False, "error": "Schema generation failed"}
        
        print(json.dumps(result))
        
    except Exception as e:
        error_result = {"success": False, "error": str(e)}
        print(json.dumps(error_result))
        sys.exit(1)

if __name__ == "__main__":
    main()