<?php

declare(strict_types=1);

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

$root = '';
$state = null;
$cleanup = null;
try {
    $root = diarR2Bootstrap($options);
    diarR2VerifyControlDatabase();
    $stale = diarR2QaCases();
    if ($stale !== []) {
        $cleanup = diarR2CleanupQaCases($root);
    }
    $protectedBefore = diarR2ProtectedCounts();
    $state = diarR2CloneQaCase($root);
    $result = diarR2RunWorkflow($root, $state);
    $keep = (string)($options['keep'] ?? '') === '1';
    if (!$keep) {
        $cleanup = diarR2CleanupQaCases($root);
        diarR2AssertProtectedCounts($protectedBefore, diarR2ProtectedCounts());
    }
    $payload = [
        'result' => 'PASS',
        'release' => DIAR_6B_4_R2_RELEASE,
        'qa_case' => ['case_code'=>$result['case_code'],'case_id'=>$result['case_id'],'site_code'=>$result['site_code']],
        'stage_path' => $result['stage_path'],
        'blocked_actions' => $result['blocked_actions'],
        'history_rows' => (int)($result['final']['history_rows'] ?? 0),
        'reopen_count' => (int)($result['final']['reopen_count'] ?? 0),
        'role_matrix' => $result['role_matrix'],
        'cleanup' => $keep ? ['kept'=>true] : $cleanup,
        'checks' => [
            'nine_stage_lifecycle' => true,
            'assignment_and_ownership' => true,
            'information_request_and_response' => true,
            'notes_and_evidence' => true,
            'finding_proposed' => true,
            'supervisor_review' => true,
            'management_approval' => true,
            'corrective_action' => true,
            'close_and_reopen' => true,
            'invalid_transitions_blocked' => true,
            'proposer_self_supervision_blocked' => true,
            'management_actor_conflict_blocked' => true,
            'sla_overdue_and_completion' => true,
            'full_audit_trail' => true,
            'frozen_identity_preserved' => true,
            'frozen_source_counts_preserved' => true,
            'qa_cleanup' => !$keep,
            'operational_mm_writes_none' => true,
            'database_link_none' => true,
        ],
    ];
    echo 'DIAR_6B_4_R2_RUNTIME_ACCEPTANCE|PASS|CASE=' . $result['case_code']
        . '|FINAL_STAGE=CLOSED|STAGE_CHECKS=' . count((array)$result['stage_path'])
        . '|BLOCKED_ACTIONS=' . count((array)$result['blocked_actions'])
        . '|HISTORY_ROWS=' . (int)($result['final']['history_rows'] ?? 0)
        . '|REOPEN_COUNT=1|ROLE_SEPARATION=PASS|FROZEN_EVIDENCE=PASS|QA_CLEANUP=' . ($keep ? 'SKIPPED_BY_REQUEST' : 'PASS')
        . '|SOURCE_MM_WRITES=NONE|DB_LINK=NONE' . PHP_EOL;
    echo json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
    exit(0);
} catch (Throwable $error) {
    $cleanupMessage = 'NOT_ATTEMPTED';
    if ($root !== '' && (string)($options['keep'] ?? '') !== '1') {
        try {
            $cleanup = diarR2CleanupQaCases($root);
            $cleanupMessage = 'PASS';
        } catch (Throwable $cleanupError) {
            $cleanupMessage = 'FAIL:' . $cleanupError->getMessage();
        }
    }
    fwrite(STDERR, 'DIAR_6B_4_R2_RUNTIME_ACCEPTANCE|FAIL|ERROR=' . $error->getMessage()
        . '|QA_CLEANUP=' . $cleanupMessage . PHP_EOL);
    exit(25);
}
