# nanobot/agent/visibility.py
"""Cryptographic signing for visibility markers to prevent model forgery."""

import hmac
import hashlib
import re

SECRET_KEY = "nanobot_visibility_secret_key_v1"


def compute_signature(content: str) -> str:
    """Compute HMAC signature for content (hex string, no prefix)."""
    return hmac.new(
        SECRET_KEY.encode(),
        content.encode(),
        hashlib.sha256
    ).hexdigest()[:8]


def sign_content(content: str) -> str:
    """
    Sign content with HMAC and prepend marker.

    Args:
        content: The message content to sign

    Returns:
        Content with signed visibility marker: "[HIDDEN:{sig}] {content}"
    """
    sig = compute_signature(content)
    return f"[HIDDEN:{sig}] {content}"


def verify_signature(marked_content: str) -> tuple[bool, str]:
    """
    Verify HMAC signature and extract clean content.

    Args:
        marked_content: Content potentially with [HIDDEN:{sig}] marker

    Returns:
        Tuple of (is_valid, clean_content)
        - is_valid: True if signature is valid, False otherwise
        - clean_content: Content without marker
    """
    match = re.match(r'\[HIDDEN:([a-f0-9]{8})\] (.*)', marked_content, re.DOTALL)
    if not match:
        return False, marked_content

    claimed_sig, content = match.groups()
    expected_sig = compute_signature(content)
    is_valid = hmac.compare_digest(claimed_sig, expected_sig)
    return is_valid, content


def has_forged_marker(content: str) -> bool:
    """
    Check if content has an invalid [HIDDEN:*] marker at the start.

    Args:
        content: Content to check

    Returns:
        True if content starts with forged marker, False otherwise
    """
    if not content.startswith("[HIDDEN:"):
        return False
    is_valid, _ = verify_signature(content)
    return not is_valid


def strip_all_hidden_markers(content: str) -> str:
    """
    Remove all [HIDDEN:*] patterns from content (valid or invalid).

    Args:
        content: Content potentially with markers

    Returns:
        Content with all markers stripped
    """
    return re.sub(r'\[HIDDEN:[a-f0-9]{8}\]\s*', '', content)
