<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

if (!cfg('debug')) {
    json_out(['ok' => false, 'error' => 'diag disabled'], 403);
}

$driver = Database::driver();
$path = cfg('db.sqlite_path');
$out = [
    'ok' => true,
    'db_driver' => $driver,
    'php_user' => get_current_user(),
    'storage_writable' => is_writable(dirname(__DIR__) . '/../storage'),
    'tables' => [],
    'reports_columns' => [],
    'test_insert' => null,
];

if ($driver === 'sqlite') {
    $out['sqlite_path'] = $path;
    $out['sqlite_realpath'] = is_string($path) ? realpath($path) : null;
    $out['sqlite_exists'] = is_string($path) && is_file($path);
    $out['sqlite_writable'] = is_string($path) && is_writable($path);
    $out['data_dir_writable'] = is_string($path) && is_writable(dirname($path));
} else {
    $m = cfg('db.mysql', []);
    $socket = trim((string) ($m['socket'] ?? ''));
    $out['mysql'] = [
        'host' => $m['host'] ?? '127.0.0.1',
        'port' => (int) ($m['port'] ?? 3306),
        'socket' => $socket,
        'socket_exists' => $socket !== '' && file_exists($socket),
        'database' => $m['database'] ?? 'androidcast_crashes',
        'username' => $m['username'] ?? '',
    ];
}

try {
    $pdo = Database::pdo();
    $tables = Database::listTables($pdo);
    $out['tables'] = $tables;
    $out['tickets_table'] = Database::ticketsTableExists($pdo);
    if (Database::isMysql()) {
        try {
            $out['mysql_database'] = $pdo->query('SELECT DATABASE()')->fetchColumn();
        } catch (Throwable $e) {
            $out['mysql_database'] = $e->getMessage();
        }
    }
    if (!$out['tickets_table']) {
        $out['tickets_migration'] = Database::ticketsMigrationHint();
    }
    if (in_array('reports', $tables, true)) {
        $cols = Database::columnNames($pdo, 'reports');
        $out['reports_columns'] = array_map(
            static fn (string $name) => ['name' => $name],
            $cols
        );
    }
    $pdo->beginTransaction();
    $stmt = $pdo->prepare(
        'INSERT INTO reports (report_id, fingerprint, crash_type, generated_at_ms, received_at_ms,
            device_model, app_version, payload_json, tags_json)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
    );
    $rid = 'diag-' . time();
    $stmt->execute([$rid, 'diag', 'java', 1, 1, null, null, '{}', '[]']);
    $pdo->rollBack();
    $out['test_insert'] = 'ok (rolled back)';
} catch (Throwable $e) {
    $out['ok'] = false;
    $out['test_insert'] = $e->getMessage();
}

json_out($out);
