<?php

declare(strict_types=1);

$framework = getenv('POC_FRAMEWORK');
$dialect = getenv('POC_DIALECT') ?: 'dm';
$root = getenv('POC_APP_ROOT');
$user = getenv('POC_USER');
$password = getenv('POC_PASSWORD');
$schema = getenv('POC_SCHEMA');
$port = (int)getenv('POC_PORT');
if (!in_array($framework, ['store', 'ai_api'], true) || !in_array($dialect, ['mysql', 'dm'], true) || !$root || !$user || !$password || !$schema || $port < 1) {
    fwrite(STDERR, "Missing isolated framework PoC settings\n");
    exit(2);
}

if ($framework === 'store') {
    define('APP_PATH', $root . '/application/');
    require $root . '/thinkphp/base.php';
    require $root . '/application/cores/database/Dm.php';
    $type = $dialect === 'dm' ? \app\cores\database\Dm::class : 'mysql';
    $prefix = 'ydy_';
    $knownTable = 'role';
} else {
    require $root . '/vendor/autoload.php';
    $type = $dialect === 'dm' ? \app\common\database\Dm::class : 'mysql';
    $prefix = 'yoshop_';
    $knownTable = 'activity';
}

$config = [
    'type' => $type,
    'hostname' => getenv('POC_HOST') ?: '127.0.0.1',
    'hostport' => $port,
    'database' => $schema,
    'username' => $user,
    'password' => $password,
    'prefix' => $prefix,
    'debug' => false,
    'fields_strict' => true,
];

if ($framework === 'store') {
    $db = \think\Db::connect($config, true);
} else {
    $manager = new \think\DbManager();
    $manager->setConfig(['default' => 'poc', 'connections' => ['poc' => $config]]);
    $db = $manager->connect('poc');
}

$tables = $db->getTables();
$fields = $db->getFields($dialect === 'dm' ? strtoupper($prefix . $knownTable) : $prefix . $knownTable);
if (count($tables) < 100 || !isset($fields['id']) || empty($fields['id']['primary'])) {
    throw new RuntimeException('DM schema metadata did not match the known table');
}
$knownRow = $db->name($knownTable)->where('id', '>', 0)->find();
if (empty($knownRow) || !isset($knownRow['id'])) {
    throw new RuntimeException('DM ORM did not return the expected lowercase row keys');
}

$table = 'CODEX_FRAMEWORK_POC_' . strtoupper(bin2hex(random_bytes(4)));
$existingTables = array_map('strtolower', $tables);
if (in_array(strtolower($table), $existingTables, true)) {
    throw new RuntimeException('PoC table name already exists');
}
$created = false;
try {
    if ($dialect === 'dm') {
        $db->execute('CREATE TABLE "' . $table . '" ("ID" INT AUTO_INCREMENT PRIMARY KEY, "V_TEXT" VARCHAR(40))');
    } else {
        $db->execute('CREATE TEMPORARY TABLE `' . $table . '` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `v_text` VARCHAR(40)) ENGINE=InnoDB');
    }
    $created = true;
    $testFields = $db->getFields($table);
    if (!isset($testFields['id']) || empty($testFields['id']['primary']) || empty($testFields['id']['autoinc'])) {
        throw new RuntimeException('DM ORM identity metadata missing');
    }

    $db->startTrans();
    $rolledBackId = $db->table($table)->insertGetId(['v_text' => '框架回滚测试']);
    $db->rollback();
    if ($db->table($table)->where('id', $rolledBackId)->count() !== 0) {
        throw new RuntimeException('DM ORM rollback left a row');
    }

    $db->startTrans();
    $id = $db->table($table)->insertGetId(['v_text' => '框架提交测试']);
    $db->commit();
    $row = $db->table($table)->where('id', $id)->find();
    if (($row['v_text'] ?? null) !== '框架提交测试') {
        throw new RuntimeException('DM ORM could not read its committed row');
    }
    $db->table($table)->where('id', $id)->update(['v_text' => '框架更新测试']);
    $row = $db->table($table)->where('id', $id)->find();
    if (($row['v_text'] ?? null) !== '框架更新测试') {
        throw new RuntimeException('DM ORM update did not persist');
    }
    $db->table($table)->where('id', $id)->delete();
    if ($db->table($table)->where('id', $id)->count() !== 0) {
        throw new RuntimeException('DM ORM delete left a row');
    }
    echo json_encode([
        'framework' => $framework,
        'dialect' => $dialect,
        'tables_seen' => count($tables),
        'known_table_fields' => count($fields),
        'query' => 'passed',
        'identity' => 'passed',
        'crud_and_transactions' => 'passed',
    ], JSON_UNESCAPED_UNICODE) . PHP_EOL;
} finally {
    if ($created) {
        $db->execute($dialect === 'dm' ? 'DROP TABLE "' . $table . '"' : 'DROP TEMPORARY TABLE `' . $table . '`');
        if ($dialect === 'dm' && in_array(strtolower($table), $db->getTables(), true)) {
            throw new RuntimeException('DM framework PoC table cleanup failed');
        }
    }
}
