<?php

declare(strict_types=1);

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

try {
    $root = diarR2Bootstrap($options);
    diarR2VerifyControlDatabase();
    $existing = diarR2QaCases();
    if ($existing !== []) {
        if ((string)($options['replace'] ?? '') !== '1') {
            throw new RuntimeException('STALE_QA_CASES_EXIST|COUNT=' . count($existing) . '|RUN_CLEANUP_OR_USE_--replace=1');
        }
        diarR2CleanupQaCases($root);
    }
    $state = diarR2CloneQaCase($root);
    echo 'DIAR_6B_4_R2_CREATE_QA_CASE|PASS|CASE_CODE=' . $state['case_code']
        . '|CASE_ID=' . $state['case_id']
        . '|SITE=' . $state['site_code']
        . '|SOURCE_CASE=' . $state['source_case_code']
        . '|STAGE=NEW|SLA=OVERDUE|QA_ONLY=PASS|SOURCE_MM_WRITES=NONE|DB_LINK=NONE' . PHP_EOL;
    exit(0);
} catch (Throwable $error) {
    fwrite(STDERR, 'DIAR_6B_4_R2_CREATE_QA_CASE|FAIL|ERROR=' . $error->getMessage() . PHP_EOL);
    exit(21);
}
