/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 * This work is published and licensed under a Creative Commons
 * Attribution-NonCommercial-NoDerivatives 4.0 International License.
 *
 * Distribution of this work is permitted, but commercial use and
 * modifications are strictly prohibited.
 */
package operator

import (
	"encoding/hex"
	"strings"
)

const sha256prefix = "sha256:"
const sha512prefix = "sha512:"

func normalizeSHADigest(digest string) string {
	if stringLikeSHA256Digest(digest) && !strings.HasPrefix(digest, sha256prefix) {
		digest = sha256prefix + digest
	} else if stringLikeSHA512Digest(digest) && !strings.HasPrefix(digest, sha512prefix) {
		digest = sha512prefix + digest
	}
	return digest
}

func stringLikeSHADigest(some string) bool {
	return stringLikeSHA256Digest(some) || stringLikeSHA512Digest(some)
}

func stringLikeSHA256Digest(some string) bool {
	if strings.HasPrefix(some, sha256prefix) {
		some = strings.TrimPrefix(some, sha256prefix)
	}
	_, err := hex.DecodeString(some)
	if err != nil {
		return false
	}
	if len(some) == 64 {
		return true
	}
	return false
}

func stringLikeSHA512Digest(some string) bool {
	if strings.HasPrefix(some, sha512prefix) {
		some = strings.TrimPrefix(some, sha512prefix)
	}
	_, err := hex.DecodeString(some)
	if err != nil {
		return false
	}
	if len(some) == 128 {
		return true
	}
	return false
}
