<?php
declare(strict_types=1);

// ── Load shared platform bootstrap first ────────────────────────────────────
define('SAVIT_ROOT', dirname(__DIR__));
require_once SAVIT_ROOT . '/Common/bootstrap.php';

// ── Content-specific constants ────────────────────────────────────────────────
define('ROOT_PATH',  __DIR__);
define('VIEWS_PATH', ROOT_PATH . '/views');

// ── Content app config (non-DB settings only) ────────────────────────────────
$appConfig = [
    'name'         => $_ENV['APP_NAME']   ?? 'Savit — Content Engine',
    'debug'        => filter_var($_ENV['APP_DEBUG'] ?? true, FILTER_VALIDATE_BOOL),
    'timezone'     => $_ENV['APP_TIMEZONE'] ?? 'Asia/Kolkata',
    'session_name' => $_ENV['SESSION_NAME'] ?? 'savit_session',
    'openai'       => [
        'api_key'     => $_ENV['OPENAI_API_KEY']     ?? '',
        'model'       => $_ENV['OPENAI_MODEL']       ?? 'gpt-4o',
        'max_tokens'  => (int)($_ENV['OPENAI_MAX_TOKENS']  ?? 4096),
        'temperature' => (float)($_ENV['OPENAI_TEMPERATURE'] ?? 0.7),
        'timeout'     => (int)($_ENV['OPENAI_TIMEOUT']  ?? 120),
    ],
];

// ── DataForSEO API credentials (shared with PPC Engine) ──────────────────────
if (!defined('DATAFORSEO_LOGIN')) {
    define('DATAFORSEO_LOGIN',    $_ENV['PPC_DATAFORSEO_LOGIN']    ?? '');
}
if (!defined('DATAFORSEO_PASSWORD')) {
    define('DATAFORSEO_PASSWORD', $_ENV['PPC_DATAFORSEO_PASSWORD'] ?? '');
}


// ── Content autoloader ────────────────────────────────────────────────────────
spl_autoload_register(function (string $class): void {
    $map = [
        'CAE\\Lib\\'                    => ROOT_PATH . '/lib/',
        'CAE\\Models\\'                 => ROOT_PATH . '/modules/models/',
        'CAE\\Modules\\ContentEngine\\' => ROOT_PATH . '/modules/content_engine/',
        'CAE\\Modules\\QAEngine\\'      => ROOT_PATH . '/modules/qa_engine/',
        'CAE\\Modules\\ExportEngine\\'  => ROOT_PATH . '/modules/export_engine/',
    ];
    foreach ($map as $prefix => $dir) {
        if (strpos($class, $prefix) === 0) {
            $file = $dir . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
            if (file_exists($file)) {
                require_once $file;
            }
            return;
        }
    }
});

// ── Detect base URL ───────────────────────────────────────────────────────────
$script = $_SERVER['SCRIPT_NAME'] ?? '/index.php';
$base   = rtrim(str_replace('index.php', '', $script), '/');
define('BASE_URL', $base);
