<?php

declare(strict_types=1);

/**
 * Lightweight MVC bootstrap — autoloads App\* classes.
 */
spl_autoload_register(static function (string $class): void {
    $prefix = 'App\\';
    if (!str_starts_with($class, $prefix)) {
        return;
    }

    $relative = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, strlen($prefix)));
    $file = dirname(__DIR__) . DIRECTORY_SEPARATOR . strtolower($relative) . '.php';

    // Map App\Services\ApiService -> services/ApiService.php
    $parts = explode(DIRECTORY_SEPARATOR, $relative);
    if (count($parts) === 2) {
        [$folder, $name] = $parts;
        $file = dirname(__DIR__) . DIRECTORY_SEPARATOR . strtolower($folder) . DIRECTORY_SEPARATOR . $name . '.php';
    }

    if (is_file($file)) {
        require_once $file;
    }
});

require_once __DIR__ . '/helpers.php';

require_once dirname(__DIR__) . '/services/ContractService.php';

function contract_service(): \App\Services\ContractService
{
    static $service = null;
    if ($service === null) {
        $service = new \App\Services\ContractService(\App\Services\ApiService::instance());
    }

    return $service;
}

function app_log_dir(): string
{
    $dir = dirname(__DIR__) . '/storage/logs';
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }

    return $dir;
}
