<?php
/**
 * Mark a Web Designer task terminal. Used by the console runner after it runs
 * the design agent + build + commit (or on failure).
 *
 *   php api/cli/tasks-finish.php --id=42 --status=published --result='{"commit":"abc123","summary":"...","live":"/about"}'
 *   php api/cli/tasks-finish.php --id=42 --status=failed --result='{"error":"build failed"}'
 *
 * status must be one of: published, failed. `result` is stored verbatim as JSON.
 */

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../config.php';

$opts = getopt('', ['id:', 'status:', 'result::']);
$id     = (int) ($opts['id'] ?? 0);
$status = (string) ($opts['status'] ?? '');
$result = (string) ($opts['result'] ?? '{}');

if ($id <= 0 || !in_array($status, ['published', 'failed'], true)) {
    fwrite(STDERR, "usage: tasks-finish.php --id=<n> --status=published|failed --result=<json>\n");
    exit(1);
}

// Validate the result payload is JSON; fall back to empty object if not.
if (json_decode($result) === null && json_last_error() !== JSON_ERROR_NONE) {
    $result = '{}';
}

$pdo = new PDO(
    sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', DB_HOST, DB_NAME),
    DB_USER,
    DB_PASS,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$stmt = $pdo->prepare(
    'UPDATE cja_tasks SET status = ?, result = ?, finished_at = NOW() WHERE task_id = ?'
);
$stmt->execute([$status, $result, $id]);

echo json_encode(['ok' => true, 'id' => $id, 'status' => $status]);
