<?php

declare(strict_types=1);

$framework = getenv('POC_FRAMEWORK');
$dialect = getenv('POC_DIALECT');
$root = getenv('POC_APP_ROOT');
$user = getenv('POC_USER');
$password = getenv('POC_PASSWORD');
$schema = getenv('POC_SCHEMA');
$host = getenv('POC_HOST') ?: '127.0.0.1';
$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 read-only scan 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';
} else {
    require $root . '/vendor/autoload.php';
    $type = $dialect === 'dm' ? \app\common\database\Dm::class : 'mysql';
}
$config = [
    'type' => $type, 'hostname' => $host, 'hostport' => $port,
    'database' => $schema, 'username' => $user, 'password' => $password,
    '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();
$failures = [];
$read = 0;
foreach ($tables as $table) {
    try {
        $fields = $db->getFields($table);
        if (!$fields) throw new RuntimeException('no fields');
        $db->table($table)->limit(1)->select();
        $read++;
    } catch (Throwable $error) {
        $failures[] = [$table, (string)$error->getCode()];
    }
}
echo json_encode([
    'framework' => $framework,
    'dialect' => $dialect,
    'tables_total' => count($tables),
    'tables_read' => $read,
    'failures' => $failures,
], JSON_UNESCAPED_UNICODE) . PHP_EOL;
if ($failures) exit(1);
