<?php
declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, "CLI only.\n");
    exit(2);
}

$target = $argv[1] ?? '';
$real = realpath($target);
$allowedRoot = realpath(__DIR__ . '/../public/generated_bots');
if ($real === false || $allowedRoot === false || !str_starts_with($real . DIRECTORY_SEPARATOR, $allowedRoot . DIRECTORY_SEPARATOR)) {
    fwrite(STDERR, "Invalid generated bot directory.\n");
    exit(2);
}
if (!is_file($real . '/table.php') || !is_file($real . '/config.php') || !is_file($real . '/tenant_db.php')) {
    fwrite(STDERR, "Child table.php/config.php/tenant_db.php missing.\n");
    exit(2);
}

chdir($real);
if (!defined('MIRZA_BUILDER_SKIP_TABLE_WEBHOOK')) define('MIRZA_BUILDER_SKIP_TABLE_WEBHOOK', true);
ob_start();
try {
    require $real . '/table.php';
    $output = trim((string)ob_get_clean());
    if (!isset($pdo) || !$pdo instanceof PDO) throw new RuntimeException('Child PDO was not created.');

    $prefix = (string)($GLOBALS['tenant_table_prefix'] ?? '');
    if (!preg_match('/^[a-z][a-z0-9_]{8,30}_$/', $prefix)) {
        throw new RuntimeException('Child table namespace is missing or invalid.');
    }

    $required = ['user', 'setting', 'admin', 'marzban_panel', 'product', 'invoice'];
    $check = $pdo->prepare('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=?');
    $missing = [];
    foreach ($required as $table) {
        $check->execute([$prefix . $table]);
        if ((int)$check->fetchColumn() !== 1) $missing[] = $table;
    }

    $countStmt = $pdo->prepare('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND LEFT(table_name, CHAR_LENGTH(?)) = ?');
    $countStmt->execute([$prefix, $prefix]);
    $count = (int)$countStmt->fetchColumn();
    if ($count < 20 || $missing) {
        throw new RuntimeException('Child table installation is incomplete. Tables: ' . $count . '; missing: ' . implode(', ', $missing));
    }

    if ($output !== '') fwrite(STDOUT, $output . PHP_EOL);
    fwrite(STDOUT, "Installed {$count} isolated child tables in namespace {$prefix}.\n");
    exit(0);
} catch (Throwable $e) {
    if (ob_get_level() > 0) $output = trim((string)ob_get_clean());
    if (!empty($output)) fwrite(STDERR, $output . PHP_EOL);
    fwrite(STDERR, $e->getMessage() . PHP_EOL);
    exit(1);
}
