<?php

declare(strict_types=1);

// DM filled-branch fixture design ONLY. No DML or business HTTP path exists.
if (($argv[1] ?? '') !== '--preflight'
    || (string)getenv('CDX_BDF_DRAFT_LANE') !== 'C') {
    fwrite(STDERR, "DM birthday filled fixture execution blocked in shared schema\n");
    exit(78);
}
set_exception_handler(static function (Throwable $e): void {
    fwrite(STDERR, 'DM filled fixture preflight failed ' . get_class($e) . ':'
        . hash('sha256', $e->getMessage()) . PHP_EOL);
    exit(1);
});
$root = '/tmp/zhct-dm-poc-20260928.fcpiiN/store';
if (is_link($root) || (string)getenv('POC_APP_ROOT') !== $root
    || (string)getenv('POC_HOST') !== '127.0.0.1'
    || (string)getenv('POC_PORT') !== '5237'
    || strtoupper((string)getenv('POC_SCHEMA')) !== 'ZHCT_APP'
    || strtoupper((string)getenv('POC_USER')) !== 'ZHCT_APP') {
    throw new RuntimeException('DM filled fixture nonproduction target drift');
}
$runtime = require $root . '/application/database.php';
if (!is_array($runtime)
    || (string)($runtime['type'] ?? '') !== 'app\\cores\\database\\Dm'
    || (string)($runtime['prefix'] ?? '') !== 'ydy_') {
    throw new RuntimeException('DM filled fixture runtime config drift');
}
foreach (['hostname' => 'POC_HOST', 'hostport' => 'POC_PORT',
    'database' => 'POC_SCHEMA', 'username' => 'POC_USER',
    'password' => 'POC_PASSWORD'] as $key => $env) {
    if ((string)($runtime[$key] ?? '') !== (string)getenv($env)) {
        throw new RuntimeException('DM filled fixture worker context drift');
    }
}
$machine = trim((string)@file_get_contents('/etc/machine-id'));
if ($machine === '' || gethostname() === false
    || hash('sha256', gethostname() . '|' . $machine)
        !== 'd56d81988bb0f106946cce91c608fdd0ef1116e5150b23376ea87e086eace4b9') {
    throw new RuntimeException('DM filled fixture host drift');
}
$listeners = [];
$listenerExit = 0;
@exec('/usr/sbin/ss -ltnp 2>/dev/null', $listeners, $listenerExit);
$localDm = false;
if ($listenerExit === 0) foreach ($listeners as $line) {
    if (preg_match('/\*:5237\s+.*users:\(\("dmserver",pid=(\d+),/', $line, $m)) {
        $exe = @readlink('/proc/' . $m[1] . '/exe');
        $localDm = is_string($exe) && basename($exe) === 'dmserver';
        break;
    }
}
if (!$localDm) throw new RuntimeException('DM filled fixture local listener absent');
$db = new PDO('dm:host=127.0.0.1;port=5237;schema=ZHCT_APP',
    (string)$runtime['username'], (string)$runtime['password'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
$identity = 'ZHCT_APP|5237|' . (string)$db->query(
    "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn();
if (hash('sha256', $identity)
    !== 'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194') {
    throw new RuntimeException('DM filled fixture database identity drift');
}
$count = static function (string $sql, array $args = []) use ($db): int {
    $stmt = $db->prepare($sql);
    $stmt->execute($args);
    return (int)$stmt->fetchColumn();
};
$required = [
    'YDY_STAFF' => ['ID', 'UUID', 'STATION_UUID', 'NAME', 'BIRTHDAY',
        'SPORT_UUID', 'SPORT_EVENT_UUID', 'CREATE_TIME', 'CREATE_BY',
        'PERSONNEL_UMBER', 'PERMANENT_ADDRESS', 'COACH_NAME', 'SPORT_YEAR'],
    'YDY_STAFF_DEPARTMENT' => ['ID', 'DEPARTMENT_UUID', 'STAFF_UUID',
        'CREATE_TIME', 'CREATE_BY'],
    'YDY_BIRTHDAY_DISH' => ['ID', 'UUID', 'STAFF_UUID', 'DISHES_UUID', 'STORE_ID'],
];
$metadata = [];
foreach ($required as $table => $fields) {
    $stmt = $db->prepare('SELECT COLUMN_NAME FROM USER_TAB_COLUMNS'
        . ' WHERE TABLE_NAME=? AND NULLABLE=? AND DATA_DEFAULT IS NULL ORDER BY COLUMN_ID');
    $stmt->execute([$table, 'N']);
    $actual = $stmt->fetchAll(PDO::FETCH_COLUMN);
    if ($actual !== $fields) throw new RuntimeException('DM filled fixture required fields drift');
    $stmt = $db->prepare('CALL SP_TABLEDEF(?, ?)');
    $stmt->execute(['ZHCT_APP', $table]);
    $ddl = $stmt->fetchColumn();
    if (is_resource($ddl)) $ddl = stream_get_contents($ddl);
    if (!preg_match('/"ID"\s+[A-Z0-9]+\s+AUTO_INCREMENT\s+NOT\s+NULL/i',
        (string)$ddl)) {
        throw new RuntimeException('DM filled fixture ID identity drift');
    }
    $stmt = $db->prepare('SELECT i.INDEX_NAME,i.UNIQUENESS,c.COLUMN_NAME'
        . ' FROM USER_INDEXES i JOIN USER_IND_COLUMNS c'
        . ' ON c.INDEX_NAME=i.INDEX_NAME AND c.TABLE_NAME=i.TABLE_NAME'
        . ' WHERE i.TABLE_NAME=? ORDER BY i.INDEX_NAME,c.COLUMN_POSITION');
    $stmt->execute([$table]);
    $groups = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $groups[(string)$row['index_name'] . '/' . (string)$row['uniqueness']][] =
            (string)$row['column_name'];
    }
    $unique = [];
    foreach ($groups as $indexKey => $columns) {
        if (substr((string)$indexKey, -7) !== '/UNIQUE') continue;
        if ($table === 'YDY_STAFF_DEPARTMENT') {
            if ($columns === ['DEPARTMENT_UUID', 'STAFF_UUID']) $unique[] = $columns;
            continue;
        }
        if ($table === 'YDY_BIRTHDAY_DISH') {
            if ($columns === ['UUID']) $unique[] = $columns;
            continue;
        }
        if ($columns === ['ID']) $unique[] = $columns;
    }
    if (count($unique) !== 1) throw new RuntimeException('DM filled fixture unique key drift');
    $triggerCount = $count('SELECT COUNT(*) FROM USER_TRIGGERS WHERE TABLE_NAME=?', [$table]);
    $outFk = $count("SELECT COUNT(*) FROM USER_CONSTRAINTS WHERE TABLE_NAME=? AND CONSTRAINT_TYPE='R'",
        [$table]);
    $inFk = $count('SELECT COUNT(*) FROM ALL_CONSTRAINTS c JOIN ALL_CONSTRAINTS parent'
        . ' ON c.R_OWNER=parent.OWNER AND c.R_CONSTRAINT_NAME=parent.CONSTRAINT_NAME'
        . " WHERE c.CONSTRAINT_TYPE='R' AND parent.OWNER='ZHCT_APP'"
        . ' AND parent.TABLE_NAME=?', [$table]);
    if ($triggerCount !== 0 || $outFk !== 0 || $inFk !== 0) {
        throw new RuntimeException('DM filled fixture FK/trigger boundary drift');
    }
    $metadata[$table] = ['required_no_default' => count($actual),
        'id_auto_increment' => true, 'expected_unique_present' => true,
        'incoming_fk' => $inFk, 'outgoing_fk' => $outFk,
        'trigger_count' => $triggerCount];
}
$department = $db->query('SELECT UUID FROM YDY_DEPARTMENT'
    . ' WHERE ID=18 AND STATUS=1 AND IS_SHOW=1 AND LEAF_FLAG=1')->fetchColumn();
$restaurant = $db->query('SELECT UUID FROM YDY_RESTAURANTS'
    . ' WHERE ID=1 AND STATUS=1 AND IS_DELETE=2')->fetchColumn();
if (!is_string($department) || $department === ''
    || !is_string($restaurant) || $restaurant === '') {
    throw new RuntimeException('DM filled fixture exact list scope drift');
}
$stmt = $db->query('SELECT ID,UUID FROM YDY_DISHES'
    . ' WHERE STORE_ID=10001 AND STATUS=1 AND IS_DEL=1 AND IS_DELETE=0'
    . ' ORDER BY ID FETCH FIRST 21 ROWS ONLY');
$dish = null;
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $candidate) {
    if ($count('SELECT COUNT(*) FROM YDY_DISHES WHERE STORE_ID=10001 AND UUID=?',
        [(string)$candidate['uuid']]) === 1) {
        $dish = $candidate;
        break;
    }
}
if (!is_array($dish)) throw new RuntimeException('DM filled fixture unique active dish absent');
$windowRows = $count('SELECT COUNT(DISTINCT s.ID) FROM YDY_STAFF s'
    . ' WHERE s.IS_SHOW=1 AND s.JOB_STATUS=1 AND s.RESTAURANT_ID=1'
    . ' AND EXISTS(SELECT 1 FROM YDY_STAFF_DEPARTMENT sd'
    . ' WHERE sd.STAFF_UUID=s.UUID AND sd.DEPARTMENT_UUID=?)'
    . ' AND DATE_FORMAT(s.BIRTHDAY,?)=?', [$department, '%m-%d', '02-29']);
$existingMarkerRows =
    $count('SELECT COUNT(*) FROM YDY_STAFF'
        . ' WHERE UUID LIKE ? OR PERSONNEL_UMBER LIKE ?', ['CDXBD2F%', 'CDXBD2F%'])
    + $count('SELECT COUNT(*) FROM YDY_STAFF_DEPARTMENT WHERE STAFF_UUID LIKE ?',
        ['CDXBD2F%'])
    + $count('SELECT COUNT(*) FROM YDY_BIRTHDAY_DISH'
        . ' WHERE STAFF_UUID LIKE ? OR UUID LIKE ?', ['CDXBD2F%', 'CDXBD2F%']);
$staffUuidTables = $count('SELECT COUNT(*) FROM USER_TAB_COLUMNS WHERE COLUMN_NAME=?',
    ['STAFF_UUID']);
if ($windowRows !== 0 || $existingMarkerRows !== 0 || $staffUuidTables < 3) {
    throw new RuntimeException('DM filled fixture zero-window/marker boundary drift');
}
echo json_encode(['lane' => 'C', 'mode' => 'select-only-preflight',
    'database_identity_approved' => true, 'local_dmserver' => true,
    'metadata' => $metadata,
    'restaurant_id' => 1, 'department_id' => 18,
    'leap_day_natural_staff_rows' => $windowRows,
    'active_unique_dish_id' => (int)$dish['id'],
    'active_unique_dish_uuid_sha12' => substr(hash('sha256', (string)$dish['uuid']), 0, 12),
    'staff_uuid_column_table_count' => $staffUuidTables,
    'old_fixture_marker_rows' => $existingMarkerRows,
    'shared_schema_active_staff_would_be_visible_to_real_lists' => true,
    'fixture_execution_supported' => false,
    'business_http_executed' => false, 'dml_executed' => false],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
