// SPDX-License-Identifier: Apache-2.0
import { IllegalArgumentError } from '../../core/errors/illegal-argument-error.js';
export class ImageReference {
    static IMAGE_TAG_REGEX = /^[\w][\w.-]{0,127}$/;
    static validateImageTag(tag, originalValue) {
        if (!tag || !ImageReference.IMAGE_TAG_REGEX.test(tag)) {
            throw new IllegalArgumentError(`Invalid image tag: ${originalValue}`, originalValue);
        }
        return tag;
    }
    static parseImageReference(imageReference) {
        const trimmedImageReference = imageReference.trim();
        if (!trimmedImageReference) {
            throw new IllegalArgumentError(`Invalid image reference format: ${imageReference}`, imageReference);
        }
        if (!trimmedImageReference.includes('/') &&
            !trimmedImageReference.includes(':') &&
            !trimmedImageReference.includes('@')) {
            throw new IllegalArgumentError(`Invalid image reference format: ${imageReference}`, imageReference);
        }
        if (trimmedImageReference.includes('@')) {
            throw new IllegalArgumentError(`Digest-based image references are not supported: ${imageReference}`, imageReference);
        }
        const lastSlash = trimmedImageReference.lastIndexOf('/');
        const lastColon = trimmedImageReference.lastIndexOf(':');
        const hasTag = lastColon > lastSlash;
        const tag = ImageReference.validateImageTag(hasTag ? trimmedImageReference.slice(lastColon + 1) : 'latest', imageReference);
        const imageWithoutTag = hasTag ? trimmedImageReference.slice(0, lastColon) : trimmedImageReference;
        const imageParts = imageWithoutTag.split('/');
        const potentialRegistry = imageParts[0];
        const explicitRegistry = potentialRegistry.includes('.') || potentialRegistry.includes(':') || potentialRegistry === 'localhost';
        const registry = explicitRegistry ? potentialRegistry : 'docker.io';
        let repository;
        if (explicitRegistry) {
            repository = imageParts.slice(1).join('/');
        }
        else if (imageParts.length === 1) {
            repository = `library/${imageParts[0]}`;
        }
        else {
            repository = imageWithoutTag;
        }
        if (!repository) {
            throw new IllegalArgumentError(`Image repository cannot be empty: ${imageReference}`, imageReference);
        }
        return { registry, repository, tag };
    }
}
//# sourceMappingURL=image-reference.js.map