<?php
declare(strict_types=1);

use CloudXM\SDK\Utilities\LoggerFactory;
use Psr\Log\LoggerInterface;

if (!function_exists('logger')) {
    /**
     * Get a PSR-3 logger for a channel.
     * - If $channel is null and we're in a class context, use that class.
     * - Otherwise, fall back to the calling file's basename.
     */
    function logger(?string $channel = null): LoggerInterface {
        if ($channel === null) {
            $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 4);
            // Prefer the nearest frame with a class
            foreach ($bt as $frame) {
                if (!empty($frame['class'])) {
                    $channel = $frame['class'];
                    break;
                }
            }
            // Fallback: file basename (procedural contexts)
            if ($channel === null) {
                $file = $bt[0]['file'] ?? ($bt[1]['file'] ?? null);
                $channel = $file ? basename($file) : 'App';
            }
        }
        return LoggerFactory::get($channel);
    }
}