<?php

declare(strict_types=1);

$options = getopt('', ['target::']);
require __DIR__ . DIRECTORY_SEPARATOR . 'diar6b4-r2-lib.php';

try {
    $root = diarR2Bootstrap($options);
    $state = diarR2LoadState($root);
    $result = diarR2RunWorkflow($root, $state);
    echo 'DIAR_6B_4_R2_WORKFLOW_FLOW|PASS|CASE_CODE=' . $result['case_code']
        . '|FINAL_STAGE=' . strtoupper((string)($result['final']['workflow_stage_code'] ?? ''))
        . '|STAGE_CHECKS=' . count((array)$result['stage_path'])
        . '|BLOCKED_ACTIONS=' . count((array)$result['blocked_actions'])
        . '|HISTORY_ROWS=' . (int)($result['final']['history_rows'] ?? 0)
        . '|REOPEN_COUNT=' . (int)($result['final']['reopen_count'] ?? 0)
        . '|ROLE_SEPARATION=PASS|FROZEN_IDENTITY=PASS|SOURCE_MM_WRITES=NONE|DB_LINK=NONE' . PHP_EOL;
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
    exit(0);
} catch (Throwable $error) {
    fwrite(STDERR, 'DIAR_6B_4_R2_WORKFLOW_FLOW|FAIL|ERROR=' . $error->getMessage() . PHP_EOL);
    exit(22);
}
