-- 🕵️ AI Visitor Tracking Database Schema
-- Trackt welche KI wann welche Artikel besucht

-- Haupt-Tabelle: AI Visitor Log
CREATE TABLE ai_visitor_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ai_name VARCHAR(50) NOT NULL,                -- 'ChatGPT', 'Claude', 'Gemini', etc.
    url VARCHAR(500) NOT NULL,                   -- Besuchte URL
    article_id INT NULL,                         -- Extrahierte Artikel-ID (falls Artikel-Seite)
    user_agent TEXT,                            -- Kompletter User-Agent String
    ip_address VARCHAR(45),                     -- IP (IPv4/IPv6)
    referer VARCHAR(500),                       -- Referer URL
    visited_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    -- Indizes für Performance
    INDEX idx_ai_name (ai_name),
    INDEX idx_article_id (article_id), 
    INDEX idx_visited_at (visited_at),
    INDEX idx_ai_article (ai_name, article_id)
);

-- AI Performance Stats (aggregierte Daten)
CREATE TABLE ai_performance_stats (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ai_name VARCHAR(50) NOT NULL,
    article_id INT NOT NULL,
    visit_count INT DEFAULT 1,
    first_visit TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_visit TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    conversion_count INT DEFAULT 0,              -- Spätere Erweiterung für Kaufabschlüsse
    
    UNIQUE KEY unique_ai_article (ai_name, article_id),
    INDEX idx_ai_performance (ai_name, visit_count DESC)
);

-- AI Schema Generation Log
CREATE TABLE ai_schema_generation_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    article_id INT NOT NULL,
    schema_type ENUM('product', 'problem_solution', 'safety') NOT NULL,
    generated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    generation_time_ms INT,                     -- Performance Monitoring
    problems_found INT DEFAULT 0,              -- Anzahl gefundener Probleme
    schema_size_kb DECIMAL(6,2),              -- Schema-Größe in KB
    success BOOLEAN DEFAULT TRUE,
    error_message TEXT NULL,
    
    INDEX idx_article_generation (article_id, generated_at),
    INDEX idx_performance (generation_time_ms, generated_at)
);

-- User-Agent Patterns für bessere KI-Erkennung
CREATE TABLE ai_detection_patterns (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ai_name VARCHAR(50) NOT NULL,
    pattern VARCHAR(200) NOT NULL,
    pattern_type ENUM('user_agent', 'referer', 'ip_range') DEFAULT 'user_agent',
    confidence_score DECIMAL(3,2) DEFAULT 1.0, -- 0.0 - 1.0 Wahrscheinlichkeit
    active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_matched TIMESTAMP NULL,
    match_count INT DEFAULT 0,
    
    INDEX idx_ai_patterns (ai_name, active),
    INDEX idx_pattern_type (pattern_type)
);

-- Initial AI Detection Patterns
INSERT INTO ai_detection_patterns (ai_name, pattern, pattern_type, confidence_score) VALUES
-- ChatGPT/OpenAI
('ChatGPT', 'GPTBot', 'user_agent', 1.0),
('ChatGPT', 'ChatGPT-User', 'user_agent', 1.0), 
('ChatGPT', 'OpenAI', 'user_agent', 0.9),
('ChatGPT', 'gpt-crawler', 'user_agent', 0.8),

-- Claude/Anthropic
('Claude', 'Claude-Web', 'user_agent', 1.0),
('Claude', 'Anthropic', 'user_agent', 0.9),
('Claude', 'claude.ai', 'referer', 1.0),

-- Google Gemini/Bard
('Gemini', 'Google-Extended', 'user_agent', 1.0),
('Gemini', 'Bard', 'user_agent', 1.0),
('Gemini', 'Gemini', 'user_agent', 1.0),
('Gemini', 'GoogleOther', 'user_agent', 0.7),
('Gemini', 'bard.google.com', 'referer', 1.0),

-- Perplexity
('Perplexity', 'PerplexityBot', 'user_agent', 1.0),
('Perplexity', 'perplexity.ai', 'referer', 1.0),

-- Microsoft Bing AI
('Bing AI', 'BingBot', 'user_agent', 0.8),
('Bing AI', 'EdgeBot', 'user_agent', 0.9),
('Bing AI', 'bing.com/chat', 'referer', 1.0),

-- Meta AI
('Meta AI', 'FacebookBot', 'user_agent', 0.7),
('Meta AI', 'facebookexternalhit', 'user_agent', 0.8),

-- Weitere aufkommende KIs
('You.com', 'YouBot', 'user_agent', 1.0),
('SearchGPT', 'SearchGPT', 'user_agent', 1.0),
('SearchGPT', 'OpenAI-SearchBot', 'user_agent', 1.0);

-- Trigger für automatische Performance Stats Update
DELIMITER $$
CREATE TRIGGER update_ai_performance_stats
    AFTER INSERT ON ai_visitor_log
    FOR EACH ROW
BEGIN
    IF NEW.article_id IS NOT NULL THEN
        INSERT INTO ai_performance_stats (ai_name, article_id, visit_count, first_visit, last_visit)
        VALUES (NEW.ai_name, NEW.article_id, 1, NEW.visited_at, NEW.visited_at)
        ON DUPLICATE KEY UPDATE
            visit_count = visit_count + 1,
            last_visit = NEW.visited_at;
    END IF;
END$$
DELIMITER ;

-- View für Dashboard: Tägliche AI Stats
CREATE VIEW daily_ai_stats AS
SELECT 
    DATE(visited_at) as visit_date,
    ai_name,
    COUNT(*) as total_visits,
    COUNT(DISTINCT ip_address) as unique_visitors,
    COUNT(DISTINCT article_id) as articles_visited,
    AVG(CASE WHEN article_id IS NOT NULL THEN 1 ELSE 0 END) as article_visit_rate
FROM ai_visitor_log
WHERE visited_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY DATE(visited_at), ai_name
ORDER BY visit_date DESC, total_visits DESC;

-- View für Top AI-besuchte Artikel
CREATE VIEW top_ai_articles AS
SELECT 
    article_id,
    SUM(visit_count) as total_ai_visits,
    COUNT(DISTINCT ai_name) as different_ais,
    GROUP_CONCAT(DISTINCT ai_name ORDER BY visit_count DESC) as top_ais,
    MAX(last_visit) as latest_ai_visit
FROM ai_performance_stats
WHERE article_id IS NOT NULL
GROUP BY article_id
ORDER BY total_ai_visits DESC
LIMIT 50;