"""0b1 Protocol Constants and Validators."""

from pathlib import Path

# Protocol constants
MAGIC_HEADER: bytes = b'\x0b\x01'
MAGIC_HEADER_HEX: str = "0b01"
API_BASE_URL: str = "https://0b1.xyz/api"
DEFAULT_KEY_PATH: Path = Path.home() / ".ob1" / "key.json"


class ProtocolError(Exception):
    """Raised when message violates 0b1 protocol."""
    pass


def validate_blob(blob_hex: str) -> bool:
    """
    Validate that encrypted blob starts with 0b01 header.
    
    Args:
        blob_hex: Hex-encoded encrypted message (e.g., "0b01a7f8...")
    
    Returns:
        True if valid
    
    Raises:
        ProtocolError: If header missing or invalid format
    """
    if not blob_hex:
        raise ProtocolError("Empty blob")
    
    # Normalize: remove 0x prefix if present
    clean = blob_hex.lower()
    if clean.startswith("0x"):
        clean = clean[2:]
    
    if not clean.startswith(MAGIC_HEADER_HEX):
        raise ProtocolError(f"Invalid header: expected '{MAGIC_HEADER_HEX}', got '{clean[:4]}'")
    
    if len(clean) < 8:  # Header + at least some data
        raise ProtocolError("Blob too short")
    
    return True


def prepend_header(data: bytes) -> bytes:
    """
    Prepend MAGIC_HEADER to raw encrypted bytes.
    
    Args:
        data: Raw ECIES ciphertext bytes
    
    Returns:
        bytes: MAGIC_HEADER + data
    """
    return MAGIC_HEADER + data


def strip_header(data: bytes) -> bytes:
    """
    Remove and validate MAGIC_HEADER from message.
    
    Args:
        data: Full message with header
    
    Returns:
        bytes: Ciphertext without header
    
    Raises:
        ProtocolError: If header invalid
    """
    if len(data) < 2:
        raise ProtocolError("Data too short for header")
    
    if data[:2] != MAGIC_HEADER:
        raise ProtocolError(f"Invalid header bytes: {data[:2].hex()}")
    
    return data[2:]
