//! Source Registry Keys — source metadata and indexes.

use super::builders::global_key;

/// Source registry key: `\x00SREG:{hash_hex}`
///
/// Stores the primary source metadata record.
pub fn source_registry_key(hash_hex: &str) -> Vec<u8> {
    global_key(b"SREG:", hash_hex.as_bytes())
}

/// Source registry scan prefix: `\x00SREG:`
///
/// Scan all source registry entries.
pub fn source_registry_scan_prefix() -> Vec<u8> {
    global_key(b"SREG:", b"")
}

/// Source registry tier index key: `\x00SREG_TIER:{tier}:{hash_hex}`
///
/// Index for listing sources by tier. Value is empty (presence only).
pub fn source_registry_tier_key(tier: u8, hash_hex: &str) -> Vec<u8> {
    let suffix = format!("{}:{}", tier, hash_hex);
    global_key(b"SREG_TIER:", suffix.as_bytes())
}

/// Source registry tier scan prefix: `\x00SREG_TIER:{tier}:`
///
/// Scan all sources for a specific tier.
pub fn source_registry_tier_prefix(tier: u8) -> Vec<u8> {
    let suffix = format!("{}:", tier);
    global_key(b"SREG_TIER:", suffix.as_bytes())
}

/// Source registry label index key: `\x00SREG_LABEL:{label_prefix}:{hash_hex}`
///
/// Index for searching sources by label prefix. Value is empty (presence only).
pub fn source_registry_label_key(label_prefix: &str, hash_hex: &str) -> Vec<u8> {
    let suffix = format!("{}:{}", label_prefix, hash_hex);
    global_key(b"SREG_LABEL:", suffix.as_bytes())
}

/// Source registry label scan prefix: `\x00SREG_LABEL:{label_prefix}`
///
/// Scan all sources whose label starts with the given prefix.
pub fn source_registry_label_prefix(label_prefix: &str) -> Vec<u8> {
    global_key(b"SREG_LABEL:", label_prefix.as_bytes())
}

/// Extract hash from a source registry tier key: `\x00SREG_TIER:{tier}:{hash_hex}`
///
/// Returns the hash_hex portion.
pub fn extract_source_registry_tier_hash(key: &[u8]) -> Option<String> {
    let prefix = b"\x00SREG_TIER:";
    if !key.starts_with(prefix) {
        return None;
    }
    let after_prefix = &key[prefix.len()..];
    // Format is {tier}:{hash_hex}
    // Find the colon after the tier number
    let colon_pos = after_prefix.iter().position(|&b| b == b':')?;
    let hash_part = &after_prefix[colon_pos + 1..];
    std::str::from_utf8(hash_part).ok().map(|s| s.to_string())
}

/// Extract hash from a source registry label key: `\x00SREG_LABEL:{label_prefix}:{hash_hex}`
///
/// Returns the hash_hex portion (last 64 characters).
pub fn extract_source_registry_label_hash(key: &[u8]) -> Option<String> {
    let key_str = std::str::from_utf8(key).ok()?;
    // Hash is always the last 64 hex chars
    if key_str.len() < 64 {
        return None;
    }
    let last_colon = key_str.rfind(':')?;
    let hash_part = &key_str[last_colon + 1..];
    if hash_part.len() == 64 && hash_part.chars().all(|c| c.is_ascii_hexdigit()) {
        Some(hash_part.to_string())
    } else {
        None
    }
}
