<?php
/**
 * ===========================================
 * FLOWBOT DCI - MAIN CONFIGURATION
 * ===========================================
 * Loads environment variables and provides configuration
 */

declare(strict_types=1);

// Load environment variables from .env file
$envFile = dirname(__DIR__) . '/.env';
$envLoaded = false;
$envErrors = [];

if (file_exists($envFile)) {
    if (is_readable($envFile)) {
        $lines = @file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if ($lines !== false) {
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line) || strpos($line, '#') === 0) continue;
                if (strpos($line, '=') === false) continue;

                $parts = explode('=', $line, 2);
                if (count($parts) !== 2) continue;

                $name = trim($parts[0]);
                $value = trim($parts[1]);

                // Remove quotes if present
                if ((substr($value, 0, 1) === '"' && substr($value, -1) === '"') ||
                    (substr($value, 0, 1) === "'" && substr($value, -1) === "'")) {
                    $value = substr($value, 1, -1);
                }

                if (!array_key_exists($name, $_ENV)) {
                    $_ENV[$name] = $value;
                    putenv("$name=$value");
                }
            }
            $envLoaded = true;
        } else {
            $envErrors[] = "Cannot read .env file contents";
        }
    } else {
        $envErrors[] = ".env file is not readable";
    }
} else {
    $envErrors[] = ".env file not found at: {$envFile}";
}

// Store env loading status for debugging
$GLOBALS['env_loaded'] = $envLoaded;
$GLOBALS['env_errors'] = $envErrors;

/**
 * Get environment variable with default fallback
 * Using function_exists to prevent redeclaration errors
 */
if (!function_exists('env')) {
    function env(string $key, $default = null) {
        $value = $_ENV[$key] ?? getenv($key);
        if ($value === false || $value === null || $value === '') {
            return $default;
        }

        // Convert string booleans
        $lowerValue = strtolower((string)$value);
        if ($lowerValue === 'true') return true;
        if ($lowerValue === 'false') return false;
        if ($lowerValue === 'null') return null;

        // Convert numeric strings
        if (is_numeric($value)) {
            return strpos($value, '.') !== false ? (float)$value : (int)$value;
        }

        return $value;
    }
}

// Application configuration array
return [
    'app' => [
        'debug' => env('APP_DEBUG', false),
        'timezone' => env('APP_TIMEZONE', 'America/Sao_Paulo'),
    ],

    'database' => [
        'host' => env('DB_HOST', 'localhost'),
        'name' => env('DB_NAME', 'digupdog_FEED'),
        'user' => env('DB_USER', 'digupdog_FEEDadmin'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => env('DB_CHARSET', 'utf8mb4'),
    ],

    // v2.2: Increased concurrency for higher throughput (VIRAL MODE optimized)
    // Phase 0: Aggressive start for maximum throughput
    // Phase 1-3: Progressive fallback for reliability
    'phases' => [
        ['concurrency' => (int)env('PHASE_0_CONCURRENCY', 100), 'timeout' => (int)env('PHASE_0_TIMEOUT', 3)],
        ['concurrency' => (int)env('PHASE_1_CONCURRENCY', 60),  'timeout' => (int)env('PHASE_1_TIMEOUT', 5)],
        ['concurrency' => (int)env('PHASE_2_CONCURRENCY', 30),  'timeout' => (int)env('PHASE_2_TIMEOUT', 8)],
        ['concurrency' => (int)env('PHASE_3_CONCURRENCY', 10),  'timeout' => (int)env('PHASE_3_TIMEOUT', 15)],
    ],

    'processing' => [
        'max_links_per_batch' => (int)env('MAX_LINKS_PER_BATCH', 10),
        'temp_folder_lifetime' => (int)env('TEMP_FOLDER_LIFETIME', 86400),
        'ssl_verify' => env('SSL_VERIFY', true),
    ],

    'defaults' => [
        'thumbnail' => env('DEFAULT_THUMBNAIL', 'fallback_image.jpg'),
        'favicon' => env('DEFAULT_FAVICON', 'default_favicon.ico'),
        'profile_picture' => env('DEFAULT_PROFILE_PICTURE', 'https://example.com/default_profile.jpg'),
        'user_password' => env('DEFAULT_USER_PASSWORD', 'ChangeMe123!'),
    ],

    'paths' => [
        'temp' => dirname(__DIR__) . '/temp',
        'views' => dirname(__DIR__) . '/views',
        'public' => dirname(__DIR__) . '/public',
    ],

    // Redis configuration (optional - falls back to file-based if unavailable)
    'redis' => [
        'enabled' => env('REDIS_ENABLED', true),
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'port' => (int)env('REDIS_PORT', 6379),
        'password' => env('REDIS_PASSWORD', null),
        'database' => (int)env('REDIS_DATABASE', 0),
        'timeout' => (int)env('REDIS_TIMEOUT', 2),
        'prefix' => env('REDIS_PREFIX', 'flowbot:'),
    ],

    // Rate limiting configuration
    'rate_limiting' => [
        'requests_per_minute' => (int)env('RATE_LIMIT_REQUESTS', 600),
        'window_seconds' => (int)env('RATE_LIMIT_WINDOW', 60),
    ],

    // v6.0: Deep Crawler configuration
    'crawler' => [
        'default_max_pages' => (int)env('CRAWLER_MAX_PAGES', 100),
        'default_max_depth' => (int)env('CRAWLER_MAX_DEPTH', 3),
        'default_parallel' => (int)env('CRAWLER_PARALLEL', 5),
        'respect_robots' => env('CRAWLER_RESPECT_ROBOTS', true),
        'user_agent' => env('CRAWLER_USER_AGENT', 'FlowbotDCI/6.0'),
        'timeout' => (int)env('CRAWLER_TIMEOUT', 10),
        'default_crawl_delay' => (int)env('CRAWLER_DELAY', 1),

        // Search engine configuration - v6.1 ALL FREE (no API keys required)
        'search_engines' => [
            // Yahoo - FREE web scraping (recommended)
            'yahoo' => [
                'enabled' => env('SEARCH_YAHOO_ENABLED', true),
                'timeout' => (int)env('SEARCH_YAHOO_TIMEOUT', 15),
                'delay_ms' => (int)env('SEARCH_YAHOO_DELAY', 2000),
            ],
            // Bing - FREE web scraping (recommended)
            'bing' => [
                'enabled' => env('SEARCH_BING_ENABLED', true),
                'timeout' => (int)env('SEARCH_BING_TIMEOUT', 15),
                'delay_ms' => (int)env('SEARCH_BING_DELAY', 3000),
                'retry_count' => (int)env('SEARCH_BING_RETRIES', 2),
            ],
            // DuckDuckGo - FREE web scraping
            'duckduckgo' => [
                'enabled' => env('SEARCH_DUCKDUCKGO_ENABLED', true),
                'timeout' => (int)env('SEARCH_DUCKDUCKGO_TIMEOUT', 15),
                'delay_ms' => (int)env('SEARCH_DUCKDUCKGO_DELAY', 2000),
            ],
            // SearXNG - FREE metasearch (public instances, may be rate-limited)
            'searxng' => [
                'enabled' => env('SEARCH_SEARXNG_ENABLED', false),
                'timeout' => (int)env('SEARCH_SEARXNG_TIMEOUT', 12),
                'delay_ms' => (int)env('SEARCH_SEARXNG_DELAY', 1500),
            ],
            // Legacy: Brave Search (requires API key)
            'brave' => [
                'enabled' => env('SEARCH_BRAVE_ENABLED', false),
                'api_key' => env('SEARCH_BRAVE_API_KEY', ''),
                'timeout' => (int)env('SEARCH_BRAVE_TIMEOUT', 15),
            ],
            // Legacy: Google (requires API key)
            'google' => [
                'enabled' => env('SEARCH_GOOGLE_ENABLED', false),
                'api_key' => env('SEARCH_GOOGLE_API_KEY', ''),
                'cx' => env('SEARCH_GOOGLE_CX', ''),
            ],
        ],
    ],
];
