<?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'];
$data = json_decode(file_get_contents('php://input'), true);

if (!$data || empty($data['comment']) || empty($data['username'])) {
    echo json_encode(['error' => 'Missing required data']);
    exit;
}

$username = $data['username'];
$comment_author = $data['author'] ?? 'Anonymous';
$comment_text = $data['comment'];

// Fetch user personality
$personality = 'funny';
try {
    $stmt = db()->prepare("SELECT ai_personality FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $personality = $stmt->fetchColumn() ?: 'funny';
} catch (Exception $e) {
    // Fallback to funny
}

$personality_instructions = "";
switch ($personality) {
    case 'serious':
        $personality_instructions = "Respond in a serious, professional, and formal tone.";
        break;
    case 'expert':
        $personality_instructions = "Respond as an expert, providing highly informative, accurate, and insightful information.";
        break;
    case 'funny':
    default:
        $personality_instructions = "Respond in a funny, engaging, and lighthearted way, using jokes or playful language.";
        break;
}

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

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

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

// Persist to DB
try {
    $stmt = db()->prepare("INSERT INTO tiktok_history (username, comment_author, comment_text, ai_reply, user_id) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$username, $comment_author, $comment_text, $ai_reply, $user_id]);
} catch (Exception $e) {
    // Log error but continue
}

echo json_encode([
    'success' => true,
    'reply' => $ai_reply,
    'author' => $comment_author,
    'comment' => $comment_text
]);
