<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Resource\Detectors;

use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Resource\ResourceDetectorInterface;
use OpenTelemetry\SDK\Resource\ResourceInfo;
use OpenTelemetry\SemConv\Incubating\Attributes\ServiceIncubatingAttributes;
use OpenTelemetry\SemConv\Version;
use Ramsey\Uuid\Uuid;

/**
 * @see https://github.com/open-telemetry/semantic-conventions/tree/main/docs/resource#service-experimental
 *
 * Spec deviation: Service Instance ID is not generated by the Service detector, as UUID is not useful in shared-nothing
 * PHP setups (FPM, Apache), and cannot be replaced by a more useful value due to Service being the last detector.
 */
final class ServiceInstance implements ResourceDetectorInterface
{
    #[\Override]
    public function getResource(): ResourceInfo
    {
        static $serviceInstanceId;
        $serviceInstanceId ??= Uuid::uuid4()->toString();

        $attributes = [
            ServiceIncubatingAttributes::SERVICE_INSTANCE_ID => $serviceInstanceId,
        ];

        return ResourceInfo::create(Attributes::create($attributes), Version::VERSION_1_38_0->url());
    }
}
