<?php

declare(strict_types=1);

// Exact one-time archive of the known rolled-back A fixture journal.
$sourceDir = '/var/folders/21/wq30qp_s6m5f1fnbzq3vq5b80000gn/T/cdx-giftlog-CDXGL5D811A7B03A13';
$archiveRoot = '/var/folders/21/wq30qp_s6m5f1fnbzq3vq5b80000gn/T/cdx-giftlog-failed-archive-20261004';
$marker = 'CDXGL5D811A7B03A13';
if (($argv[1] ?? '') !== '--archive-exact'
    || (string)getenv('CDX_GIFT_ARCHIVE_APPROVED') !== 'ROOT_APPROVED_GIFT_FAILED_ARCHIVE_V1'
    || (string)getenv('CDX_GIFT_ARCHIVE_SHA') !== hash_file('sha256', __FILE__)) {
    echo json_encode(['status' => 'default_deny', 'db_dml' => 0,
        'business_http' => 0, 'file_move' => 0]), PHP_EOL;
    exit(78);
}
$stage = 'journal_identity';
set_exception_handler(static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'archive_stopped', 'stage' => $stage,
        'class' => get_class($error), 'sql_code' => (string)$error->getCode(),
        'reason_sha' => hash('sha256', $error->getMessage()),
        'db_dml' => 0, 'business_http' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(2);
});
$journalPath = $sourceDir . '/fixture.json';
if (is_link($sourceDir) || is_link($journalPath)
    || !is_dir($sourceDir) || !is_file($journalPath)
    || (((int)fileperms($sourceDir) & 0077) !== 0)
    || (((int)fileperms($journalPath) & 0077) !== 0)
    || file_exists($archiveRoot) || is_link($archiveRoot)) {
    throw new RuntimeException('Exact source or empty destination boundary failed');
}
$journal = json_decode((string)file_get_contents($journalPath), true);
if (!is_array($journal) || ($journal['marker'] ?? '') !== $marker
    || ($journal['lane_group'] ?? '') !== 'AB'
    || ($journal['state'] ?? '') !== 'requires_manual_check_after_insert_error'
    || ($journal['period'] ?? null)
        !== ['2026-09-01 00:00:00', '2026-10-01 00:00:00']
    || ($journal['log_ids'] ?? null) !== []
    || !empty($journal['tokens']) || !empty($journal['http_states'])) {
    throw new RuntimeException('Known failed fixture journal values drifted');
}
$sourceEntries = array_values(array_diff(scandir($sourceDir) ?: [], ['.', '..']));
sort($sourceEntries, SORT_STRING);
if ($sourceEntries !== ['fixture.json']) {
    throw new RuntimeException('Failed fixture directory has unexpected files');
}
$stage = 'approved_database_identity';
$base = __DIR__ . '/../parallel-ai-next-read-safe4/read2_schema_preflight.php';
if (!is_file($base) || hash_file('sha256', $base)
    !== '8641ee015ad537d300de9c00f2c882e654b739d7c2194dd13ef4635ca9df1af0') {
    throw new RuntimeException('A local identity preflight drift');
}
putenv('CDX_READ2_TARGET=A');
putenv('CDX_READ2_SCHEMA_PREFLIGHT=1');
require $base;
$ai->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$store->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$fingerprint = static function (PDO $pdo): string {
    return hash('sha256', (string)$pdo->query(
        "SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")
        ->fetchColumn());
};
if ($fingerprint($ai)
        !== '210f925e093f71e26a8c8923f0f626e3be0a15ccff3d386bba21feef695c8a5b'
    || $fingerprint($store)
        !== '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401') {
    throw new RuntimeException('A code-local AI/Store physical database identity drift');
}
$one = static function (PDO $pdo, string $sql, array $args): array {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($args);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (count($rows) !== 1) throw new RuntimeException('Controlled actor not unique');
    $out = [];
    foreach (array_change_key_case($rows[0], CASE_LOWER) as $name => $value) {
        $out[$name] = is_resource($value) ? stream_get_contents($value) : $value;
    }
    return $out;
};
$digest = static function (array $row): string {
    ksort($row, SORT_STRING);
    return hash('sha256', serialize($row));
};
$count = static function (PDO $pdo, string $sql, array $args = []): int {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($args);
    return (int)$stmt->fetchColumn();
};
$stage = 'exact_marker_and_actor_zero';
if ($count($ai, 'SELECT COUNT(*) FROM yoshop_user_gift_log'
        . ' WHERE IDEMPOTENCY_KEY LIKE ?', [$marker . '%']) !== 0
    || $count($ai, 'SELECT COUNT(*) FROM yoshop_user_gift_log'
        . " WHERE IDEMPOTENCY_KEY LIKE 'CDXGL5%'") !== 0
    || $count($ai, 'SELECT COUNT(*) FROM yoshop_user'
        . " WHERE NICK_NAME LIKE 'CDXGL5%' AND STORE_ID=10001") !== 0) {
    throw new RuntimeException('Failed fixture marker not independently zero');
}
$owned = ['owner' => 'CDXPARMOB426CA4B0', 'foreign' => 'CDXPAY112FC189'];
foreach ($owned as $role => $nickname) {
    $id = (int)($journal['owner_ids'][$role] ?? 0);
    if ($id <= 0) throw new RuntimeException('Failed journal user ID invalid');
    $user = $one($ai, 'SELECT * FROM yoshop_user'
        . ' WHERE USER_ID=? AND NICK_NAME=? AND STORE_ID=10001 AND IS_DELETE=0',
        [$id, $nickname]);
    $mapping = $one($store, 'SELECT * FROM ydy_user'
        . ' WHERE AI_USER_ID=? AND IS_DELETE=0', [$id]);
    if ($digest($user) !== (string)($journal['user_hashes'][$role] ?? '')
        || $digest($mapping) !== (string)($journal['store_hashes'][$role] ?? '')
        || $count($ai, 'SELECT COUNT(*) FROM yoshop_user_gift_log'
            . ' WHERE USER_ID=? AND CREATE_TIME>=? AND CREATE_TIME<?',
            [$id, '2026-09-01 00:00:00', '2026-10-01 00:00:00']) !== 0) {
        throw new RuntimeException('Failed fixture actor row or candidate month drift');
    }
}
$stage = 'archive_destination_absence';
if (file_exists($archiveRoot) || is_link($archiveRoot)
    || file_exists($archiveRoot . '/' . basename($sourceDir))) {
    throw new RuntimeException('Archive destination already exists');
}
if (!mkdir($archiveRoot, 0700) || !chmod($archiveRoot, 0700)) {
    throw new RuntimeException('Private archive root creation failed');
}
$stage = 'same_volume_no_overwrite_rename';
$destination = $archiveRoot . '/' . basename($sourceDir);
if (file_exists($destination) || is_link($destination)
    || !rename($sourceDir, $destination)) {
    throw new RuntimeException('Exact failed journal directory move failed');
}
if (!is_dir($destination) || !is_file($destination . '/fixture.json')
    || (((int)fileperms($archiveRoot) & 0077) !== 0)
    || (((int)fileperms($destination) & 0077) !== 0)
    || (((int)fileperms($destination . '/fixture.json') & 0077) !== 0)
    || file_exists($sourceDir)) {
    throw new RuntimeException('Archive post-move ownership/mode failed');
}
echo json_encode(['status' => 'failed_fixture_archived',
    'archive_directory' => $destination,
    'journal_mode' => '0600', 'directory_mode' => '0700',
    'exact_marker_rows' => 0, 'candidate_month_rows' => 0,
    'actor_and_store_rows_unchanged' => true,
    'business_http' => 0, 'db_dml' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
