<?php

declare(strict_types=1);

$root = getenv('POC_APP_ROOT');
$password = getenv('POC_PASSWORD');
if (!$root || !$password) exit(2);
require $root . '/vendor/autoload.php';

$manager = new \think\DbManager();
$manager->setConfig([
    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            'type' => \app\common\database\Dm::class,
            'hostname' => '127.0.0.1',
            'hostport' => 5238,
            'database' => 'AIZHCT_APP',
            'username' => 'AIZHCT_APP',
            'password' => 'not-used',
            'prefix' => 'yoshop_',
        ],
        'mysql_zhct' => [
            'type' => \app\common\database\Dm::class,
            'hostname' => '127.0.0.1',
            'hostport' => 5237,
            'database' => 'ZHCT_APP',
            'username' => 'ZHCT_APP',
            'password' => $password,
            'prefix' => 'ydy_',
        ],
    ],
]);

$db = $manager->connect('mysql_zhct');
$fields = $db->getFields('YDY_ROLE');
if (!isset($fields['id']) || empty($fields['id']['primary'])) {
    throw new RuntimeException('Store schema metadata unavailable through AI cross-connection');
}
$row = $db->name('role')->where('id', '>', 0)->find();
if (empty($row) || !isset($row['id'])) {
    throw new RuntimeException('Store data unavailable through AI cross-connection');
}

$table = 'CODEX_CROSS_POC_' . strtoupper(bin2hex(random_bytes(4)));
if (in_array(strtolower($table), array_map('strtolower', $db->getTables()), true)) {
    throw new RuntimeException('Cross-connection probe table already exists');
}
$created = false;
try {
    $db->execute('CREATE TABLE "' . $table . '" ("ID" INT AUTO_INCREMENT PRIMARY KEY, "VALUE_TEXT" VARCHAR(30))');
    $created = true;
    $id = $db->table($table)->insertGetId(['value_text' => 'ai-to-store']);
    $saved = $db->table($table)->where('id', $id)->find();
    if (($saved['value_text'] ?? null) !== 'ai-to-store') {
        throw new RuntimeException('Cross-connection write did not persist');
    }
    echo json_encode(['cross_connection' => 'passed', 'store_table' => 'ydy_role', 'write_readback' => 'passed']) . PHP_EOL;
} finally {
    if ($created) {
        $db->execute('DROP TABLE "' . $table . '"');
        if (in_array(strtolower($table), array_map('strtolower', $db->getTables()), true)) {
            throw new RuntimeException('Cross-connection probe cleanup failed');
        }
    }
}
