<?php

declare(strict_types=1);

/**
 * Application bootstrap: paths, Composer autoload, core constants.
 * Do not store secrets here — use config/local.php (generated by installer, not in VCS).
 */

$seoscopeRoot = dirname(__DIR__);

if (!defined('SEOSCOPE_ROOT')) {
    define('SEOSCOPE_ROOT', $seoscopeRoot);
}

$autoload = SEOSCOPE_ROOT . '/vendor/autoload.php';
if (is_readable($autoload)) {
    require_once $autoload;
} else {
    // M0 fallback: PSR-4-like autoload if composer install was not run
    spl_autoload_register(static function (string $class): void {
        $prefix = 'SeoScope\\';
        if (strncmp($prefix, $class, strlen($prefix)) !== 0) {
            return;
        }
        $rel = substr($class, strlen($prefix));
        $path = SEOSCOPE_ROOT . '/app/' . str_replace('\\', '/', $rel) . '.php';
        if (is_readable($path)) {
            require_once $path;
        }
    });
    require_once SEOSCOPE_ROOT . '/app/i18n/helpers.php';
}

if (!defined('SEOSCOPE_VERSION')) {
    define('SEOSCOPE_VERSION', \SeoScope\Version::VERSION);
}

$configExample = SEOSCOPE_ROOT . '/config/config.example.php';
$configLocal = SEOSCOPE_ROOT . '/config/local.php';

if (!defined('SEOSCOPE_TABLE_PREFIX')) {
    if (is_readable($configLocal)) {
        $local = require $configLocal;
        define('SEOSCOPE_TABLE_PREFIX', (string) ($local['db']['table_prefix'] ?? 'sscope_'));
    } elseif (is_readable($configExample)) {
        $example = require $configExample;
        define('SEOSCOPE_TABLE_PREFIX', (string) ($example['db']['table_prefix'] ?? 'sscope_'));
    } else {
        define('SEOSCOPE_TABLE_PREFIX', 'sscope_');
    }
}
