<?php
/**
 * Minimal PSR-4-style autoloader tailored to WordPress class-file conventions.
 *
 * Maps Backreload\Foo\BarBaz -> includes/foo/class-bar-baz.php
 *
 * @package Backreload
 */

namespace Backreload;

if ( ! defined( 'ABSPATH' ) ) { exit; }

final class Autoloader {

	/** @var string */
	private $prefix;

	/** @var string */
	private $base_dir;

	public function __construct( string $prefix, string $base_dir ) {
		$this->prefix   = $prefix;
		$this->base_dir = trailingslashit( $base_dir );
	}

	public function register(): void {
		spl_autoload_register( [ $this, 'load' ] );
	}

	public function load( string $class ): void {
		if ( strpos( $class, $this->prefix ) !== 0 ) {
			return;
		}

		$relative = substr( $class, strlen( $this->prefix ) );
		$parts    = explode( '\\', $relative );
		$class_nm = array_pop( $parts );
		$kebab    = self::kebab( $class_nm );
		$path     = strtolower( implode( '/', $parts ) );
		$dir      = $this->base_dir . ( $path ? $path . '/' : '' );

		// Try the WP-style prefixes in order. Same symbol can be defined as a
		// class, interface, trait, or abstract class — we don't know which up front.
		foreach ( [ 'class', 'interface', 'abstract', 'trait' ] as $prefix ) {
			$file = $dir . $prefix . '-' . $kebab . '.php';
			if ( file_exists( $file ) ) {
				require_once $file;
				return;
			}
		}
	}

	private static function kebab( string $name ): string {
		$name = preg_replace( '/([a-z0-9])([A-Z])/', '$1-$2', $name );
		$name = preg_replace( '/([A-Z]+)([A-Z][a-z])/', '$1-$2', $name );
		return strtolower( $name );
	}
}
