<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('ok' => false, 'error' => 'Method Not Allowed'));
    exit;
}

require_csrf();

$taskId  = isset($_POST['task_id'])  ? (int)$_POST['task_id']  : 0;
$modelId = isset($_POST['model_id']) ? (int)$_POST['model_id'] : 0;

if ($taskId <= 0 || $modelId <= 0) {
    echo json_encode(array('ok' => false, 'error' => '参数无效。'), JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $task = find_article_generation_task_by_id($taskId);
    if (!$task) {
        throw new Exception('未找到对应的任务。');
    }

    $model = find_ai_model_by_id($modelId);
    if (!$model || (isset($model['status']) && $model['status'] !== 'enabled')) {
        throw new Exception('所选模型不可用或已停用。');
    }

    $pdo = db_connection();
    $stmt = $pdo->prepare('UPDATE article_generation_tasks SET model_id = :model_id, updated_at = :updated_at WHERE id = :id LIMIT 1');
    $stmt->execute(array(
        ':model_id'   => $modelId,
        ':updated_at' => date('Y-m-d H:i:s'),
        ':id'         => $taskId
    ));

    $displayName = isset($model['name']) ? trim((string)$model['name']) : ('模型#' . $modelId);

    echo json_encode(array('ok' => true, 'model_name' => $displayName), JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    echo json_encode(array('ok' => false, 'error' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
}
