<?php
header('Content-Type: application/json');
session_start();
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../ai/LocalAIApi.php';

// Authentication check
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$username = $_GET['username'] ?? '';

if (empty($username)) {
    echo json_encode(['events' => []]);
    exit;
}

try {
    // 1. Fetch pending comments (those without AI replies) for this specific user
    $stmt = db()->prepare("SELECT * FROM tiktok_history WHERE username = ? AND user_id = ? AND ai_reply IS NULL ORDER BY created_at ASC LIMIT 5");
    $stmt->execute([$username, $user_id]);
    $pending = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $results = [];

    foreach ($pending as $row) {
        $comment_author = $row['comment_author'];
        $comment_text = $row['comment_text'];

        // 2. Generate AI Reply
        $prompt = "You are a helpful and funny AI assistant for a TikTok live stream. 
        The streamer is '$username'. 
        The user '$comment_author' just said: '$comment_text'. 
        Respond to them in a short, engaging, and friendly way (max 20 words). 
        Keep it suitable for a live stream audience.";

        $resp = LocalAIApi::createResponse([
            'input' => [
                ['role' => 'system', 'content' => 'TikTok Live AI Assistant'],
                ['role' => 'user', 'content' => $prompt],
            ],
        ]);

        $ai_reply = '';
        if (!empty($resp['success'])) {
            $ai_reply = LocalAIApi::extractText($resp);
        } else {
            $ai_reply = "Thanks for your comment, $comment_author!";
        }

        // 3. Update DB
        $update = db()->prepare("UPDATE tiktok_history SET ai_reply = ? WHERE id = ?");
        $update->execute([$ai_reply, $row['id']]);

        $results[] = [
            'id' => $row['id'],
            'author' => $comment_author,
            'comment' => $comment_text,
            'reply' => $ai_reply,
            'timestamp' => $row['created_at']
        ];
    }

    // 4. Also fetch recently processed comments (last 5 seconds) for this user
    $since = date('Y-m-d H:i:s', time() - 5);
    $stmt = db()->prepare("SELECT * FROM tiktok_history WHERE username = ? AND user_id = ? AND ai_reply IS NOT NULL AND created_at >= ? ORDER BY created_at DESC LIMIT 10");
    $stmt->execute([$username, $user_id, $since]);
    $processed = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Merge if needed, but for polling, we just return the newly processed ones usually
    echo json_encode(['events' => $results]);

} catch (Exception $e) {
    error_log("Update Error: " . $e->getMessage());
    echo json_encode(['error' => $e->getMessage(), 'events' => []]);
}