#!/usr/bin/env python3
"""
🎛️ Intelectra AI Control Center - Flask Dashboard
Trackt KI-Besucher und steuert FAQ/Schema System
"""

from flask import Flask, render_template, request, jsonify, redirect, url_for, flash
import mysql.connector
import json
import re
from datetime import datetime, timedelta
import os
from config import DB_CONFIG

app = Flask(__name__)
app.secret_key = 'intelectra_ai_dashboard_secret_2025'

class AIAdminDashboard:
    def __init__(self):
        self.db_config = DB_CONFIG
        
        # KI-Detection Patterns
        self.ai_signatures = {
            'ChatGPT': ['GPTBot', 'ChatGPT-User', 'OpenAI', 'gpt-crawler'],
            'Claude': ['Claude-Web', 'Anthropic', 'Claude', 'anthropic'],
            'Gemini': ['Google-Extended', 'Bard', 'Gemini', 'GoogleOther'],
            'Perplexity': ['PerplexityBot', 'perplexity'],
            'Bing AI': ['BingBot', 'EdgeBot', 'msnbot'],
            'Meta AI': ['FacebookBot', 'Meta', 'facebookexternalhit'],
            'You.com': ['YouBot', 'you.com'],
            'SearchGPT': ['SearchGPT', 'OpenAI-SearchBot']
        }
    
    def get_db_connection(self):
        """Sichere DB-Verbindung"""
        try:
            return mysql.connector.connect(**self.db_config)
        except Exception as e:
            print(f"DB Connection failed: {e}")
            return None
    
    def detect_ai_visitor(self, user_agent, referer=''):
        """Erkennt KI-Besucher anhand User-Agent & Referer"""
        user_agent = user_agent.lower()
        referer = referer.lower()
        
        for ai_name, signatures in self.ai_signatures.items():
            for signature in signatures:
                if signature.lower() in user_agent or signature.lower() in referer:
                    return ai_name
        
        return None
    
    def log_ai_visit(self, ai_name, url, user_agent, ip_address, referer=''):
        """Loggt KI-Besuch in Datenbank"""
        try:
            conn = self.get_db_connection()
            if not conn:
                return False
                
            cursor = conn.cursor()
            
            # Artikel-ID aus URL extrahieren
            article_id = None
            url_match = re.search(r'/artikel/(\d+)', url)
            if url_match:
                article_id = int(url_match.group(1))
            
            query = """
                INSERT INTO ai_visitor_log 
                (ai_name, url, article_id, user_agent, ip_address, referer, visited_at)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
            """
            
            cursor.execute(query, (ai_name, url, article_id, user_agent, ip_address, referer, datetime.now()))
            conn.commit()
            
            cursor.close()
            conn.close()
            return True
            
        except Exception as e:
            print(f"AI visit logging failed: {e}")
            return False
    
    def get_ai_stats(self, days=7):
        """Holt KI-Statistiken der letzten N Tage"""
        try:
            conn = self.get_db_connection()
            if not conn:
                return {}
                
            cursor = conn.cursor(dictionary=True)
            
            # Basis-Statistiken
            since_date = datetime.now() - timedelta(days=days)
            
            # KI-Besuche pro AI
            cursor.execute("""
                SELECT ai_name, COUNT(*) as visit_count,
                       COUNT(DISTINCT ip_address) as unique_visitors
                FROM ai_visitor_log 
                WHERE visited_at >= %s 
                GROUP BY ai_name 
                ORDER BY visit_count DESC
            """, (since_date,))
            
            ai_visits = cursor.fetchall()
            
            # Top besuchte Artikel
            cursor.execute("""
                SELECT avl.article_id, COUNT(*) as visit_count,
                       GROUP_CONCAT(DISTINCT avl.ai_name) as visiting_ais
                FROM ai_visitor_log avl
                WHERE avl.visited_at >= %s AND avl.article_id IS NOT NULL
                GROUP BY avl.article_id 
                ORDER BY visit_count DESC 
                LIMIT 10
            """, (since_date,))
            
            top_articles = cursor.fetchall()
            
            # Zeitverteilung (Stunden)
            cursor.execute("""
                SELECT HOUR(visited_at) as hour, COUNT(*) as visits
                FROM ai_visitor_log 
                WHERE visited_at >= %s 
                GROUP BY HOUR(visited_at)
                ORDER BY hour
            """, (since_date,))
            
            hourly_distribution = cursor.fetchall()
            
            cursor.close()
            conn.close()
            
            return {
                'ai_visits': ai_visits,
                'top_articles': top_articles,
                'hourly_distribution': hourly_distribution,
                'period_days': days
            }
            
        except Exception as e:
            print(f"Stats retrieval failed: {e}")
            return {}

# Flask Dashboard Routes
dashboard = AIAdminDashboard()

@app.route('/')
def dashboard_home():
    """Hauptdashboard mit KI-Statistiken"""
    stats = dashboard.get_ai_stats(days=7)
    return render_template('dashboard.html', stats=stats)

@app.route('/faq-management')
def faq_management():
    """FAQ/Problem Management Interface"""
    try:
        conn = dashboard.get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        # Alle Probleme laden
        cursor.execute("""
            SELECT * FROM problem_solutions 
            WHERE active = TRUE 
            ORDER BY frequency_score DESC
        """)
        problems = cursor.fetchall()
        
        cursor.close()
        conn.close()
        
        return render_template('faq_management.html', problems=problems)
        
    except Exception as e:
        flash(f'Error loading problems: {e}', 'error')
        return redirect(url_for('dashboard_home'))

@app.route('/add-problem', methods=['GET', 'POST'])
def add_problem():
    """Neues Problem hinzufügen"""
    if request.method == 'POST':
        try:
            conn = dashboard.get_db_connection()
            cursor = conn.cursor()
            
            # Form-Daten extrahieren
            data = {
                'problem_category': request.form['category'],
                'problem_title': request.form['title'],
                'problem_description': request.form['description'],
                'symptoms': json.dumps(request.form['symptoms'].split('\n')),
                'keywords': json.dumps(request.form['keywords'].split(',')),
                'urgency_level': request.form['urgency'],
                'repair_complexity': request.form['complexity'],
                'frequency_score': int(request.form.get('frequency', 50))
            }
            
            query = """
                INSERT INTO problem_solutions 
                (problem_category, problem_title, problem_description, symptoms, 
                 keywords, urgency_level, repair_complexity, frequency_score)
                VALUES (%(problem_category)s, %(problem_title)s, %(problem_description)s, 
                        %(symptoms)s, %(keywords)s, %(urgency_level)s, 
                        %(repair_complexity)s, %(frequency_score)s)
            """
            
            cursor.execute(query, data)
            conn.commit()
            
            cursor.close()
            conn.close()
            
            flash('Problem erfolgreich hinzugefügt!', 'success')
            return redirect(url_for('faq_management'))
            
        except Exception as e:
            flash(f'Error adding problem: {e}', 'error')
    
    return render_template('add_problem.html')

@app.route('/api/ai-visits')
def api_ai_visits():
    """API Endpoint für Live AI-Visit Updates"""
    stats = dashboard.get_ai_stats(days=1)
    return jsonify(stats)

@app.route('/api/detect-visitor', methods=['POST'])
def api_detect_visitor():
    """API Endpoint für KI-Visitor Detection (wird vom PHP Shop aufgerufen)"""
    try:
        data = request.json
        user_agent = data.get('user_agent', '')
        url = data.get('url', '')
        ip_address = data.get('ip_address', '')
        referer = data.get('referer', '')
        
        # KI erkennen
        ai_name = dashboard.detect_ai_visitor(user_agent, referer)
        
        if ai_name:
            # In DB loggen
            dashboard.log_ai_visit(ai_name, url, user_agent, ip_address, referer)
            
            return jsonify({
                'ai_detected': True,
                'ai_name': ai_name,
                'logged': True
            })
        else:
            return jsonify({
                'ai_detected': False,
                'ai_name': None,
                'logged': False
            })
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/schema-preview/<int:article_id>')
def schema_preview(article_id):
    """Live Preview des generierten AI Schemas für einen Artikel"""
    # Hier würde das AI Schema für den Artikel generiert und angezeigt
    return render_template('schema_preview.html', article_id=article_id)

if __name__ == '__main__':
    # Development Server - NUR für Testing!
    app.run(host='127.0.0.1', port=5000, debug=True)