<?php

declare(strict_types=1);

$root = getenv('POC_APP_ROOT');
$password = getenv('POC_PASSWORD');
if (!$root || !$password) exit(2);
define('APP_PATH', $root . '/application/');
require $root . '/thinkphp/base.php';
require $root . '/application/common.php';
require $root . '/application/cores/database/Dm.php';
if (!function_exists('config')) {
    function config($name = '', $value = null, $range = '')
    {
        return $value === null ? \think\Config::get($name) : \think\Config::set($name, $value, $range);
    }
}

\think\Config::set([
    'type' => \app\cores\database\Dm::class,
    'hostname' => '127.0.0.1',
    'hostport' => 5237,
    'database' => 'ZHCT_APP',
    'username' => 'ZHCT_APP',
    'password' => 'not-used',
    'prefix' => 'ydy_',
    'fields_strict' => true,
    'ai_zhct' => [
        'hostname' => '127.0.0.1',
        'hostport' => 5238,
        'database' => 'AIZHCT_APP',
        'username' => 'AIZHCT_APP',
        'password' => $password,
        'prefix' => 'yoshop_',
    ],
], 'database');

$db = get_ai_db();
$fields = $db->getFields('YOSHOP_ACTIVITY');
if (!isset($fields['id']) || !isset($fields['id']['primary'])) {
    throw new RuntimeException('AI schema metadata unavailable through store cross-connection');
}
$row = $db->name('activity')->where('id', '>', 0)->find();
if (empty($row) || !isset($row['id'])) {
    throw new RuntimeException('AI data unavailable through store 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' => 'store-to-ai']);
    $saved = $db->table($table)->where('id', $id)->find();
    if (($saved['value_text'] ?? null) !== 'store-to-ai') {
        throw new RuntimeException('Cross-connection write did not persist');
    }
    echo json_encode(['cross_connection' => 'passed', 'ai_table' => 'yoshop_activity', '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');
        }
    }
}
