<?php

if (defined('LEGACY_MODULE_BOOTSTRAPPED')) {
    return;
}

define('LEGACY_MODULE_BOOTSTRAPPED', true);
define('LEGACY_MODULE_ROOT', __DIR__);
define('LEGACY_MODULE_CONFIG_DIR', LEGACY_MODULE_ROOT . '/config');
define('LEGACY_MODULE_LOCAL_CONFIG', LEGACY_MODULE_CONFIG_DIR . '/local.php');
define('LEGACY_MODULE_EXAMPLE_CONFIG', LEGACY_MODULE_CONFIG_DIR . '/local.example.php');

function legacy_default_config() {
    return [
        'db' => [
            'host' => '127.0.0.1',
            'port' => 3306,
            'database' => '',
            'user' => '',
            'password' => '',
            'charset' => 'utf8',
        ],
        'openai' => [
            'api_key' => '',
            'model' => 'gpt-4o-mini',
            'endpoint' => 'https://api.openai.com/v1/chat/completions',
        ],
        'store' => [
            'name' => 'Natural - Mercado de Vida',
            'language_es' => 4,
            'language_en' => 1,
            'image_base_url' => 'https://example.local/image/',
            'product_base_url' => 'https://example.local/index.php?route=product/product&product_id=',
        ],
        'routes' => [
            'login_url' => '../login.php',
            'success_url' => 'https://example.local/producto-nuevo/success.php',
        ],
        'security' => [
            'form_password_hash' => '',
        ],
        'paths' => [
            'log_dir' => LEGACY_MODULE_ROOT . '/logs',
            'worker_log' => LEGACY_MODULE_ROOT . '/logs/worker.log',
            'prompt_en' => LEGACY_MODULE_ROOT . '/inc/prompt_en.md',
            'prompt_es' => LEGACY_MODULE_ROOT . '/inc/prompt_es.md',
        ],
        'worker' => [
            'batch_size' => 20,
            'min_html_length' => 500,
        ],
    ];
}

function legacy_deep_merge(array $base, array $override) {
    foreach ($override as $key => $value) {
        if (is_array($value) && isset($base[$key]) && is_array($base[$key])) {
            $base[$key] = legacy_deep_merge($base[$key], $value);
            continue;
        }
        $base[$key] = $value;
    }
    return $base;
}

function legacy_config_file_data($path) {
    if (!is_file($path)) {
        return [];
    }

    $data = require $path;
    return is_array($data) ? $data : [];
}

function legacy_normalize_config(array $config) {
    foreach (['image_base_url', 'product_base_url'] as $key) {
        if (isset($config['store'][$key])) {
            $config['store'][$key] = trim((string)$config['store'][$key]);
        }
    }

    if (isset($config['routes']['login_url'])) {
        $config['routes']['login_url'] = trim((string)$config['routes']['login_url']);
    }

    if (isset($config['routes']['success_url'])) {
        $config['routes']['success_url'] = trim((string)$config['routes']['success_url']);
    }

    return $config;
}

$legacy_config = legacy_default_config();
$legacy_config_source = LEGACY_MODULE_EXAMPLE_CONFIG;

if (is_file(LEGACY_MODULE_LOCAL_CONFIG)) {
    $legacy_config = legacy_deep_merge($legacy_config, legacy_config_file_data(LEGACY_MODULE_LOCAL_CONFIG));
    $legacy_config_source = LEGACY_MODULE_LOCAL_CONFIG;
} elseif (is_file(LEGACY_MODULE_EXAMPLE_CONFIG)) {
    $legacy_config = legacy_deep_merge($legacy_config, legacy_config_file_data(LEGACY_MODULE_EXAMPLE_CONFIG));
}

$legacy_config = legacy_normalize_config($legacy_config);

function legacy_config_all() {
    global $legacy_config;
    return $legacy_config;
}

function legacy_config($path, $default = null) {
    $value = legacy_config_all();
    foreach (explode('.', $path) as $segment) {
        if (!is_array($value) || !array_key_exists($segment, $value)) {
            return $default;
        }
        $value = $value[$segment];
    }
    return $value;
}

function legacy_config_source() {
    global $legacy_config_source;
    return $legacy_config_source;
}

function legacy_new_mysqli() {
    $host = legacy_config('db.host', '127.0.0.1');
    $user = legacy_config('db.user', '');
    $password = legacy_config('db.password', '');
    $database = legacy_config('db.database', '');
    $port = (int) legacy_config('db.port', 3306);
    $charset = legacy_config('db.charset', 'utf8');

    $db = new mysqli($host, $user, $password, $database, $port);
    if (!$db->connect_errno && $charset) {
        $db->set_charset($charset);
    }

    return $db;
}
