"""Shannon entropy calculation for secret detection."""

from __future__ import annotations

import math
import re

_B64_CHARS = re.compile(r"^[A-Za-z0-9+/=]{20,}$")
_HEX_CHARS = re.compile(r"^[0-9a-fA-F]{20,}$")
_ALPHANUM = re.compile(r"^[A-Za-z0-9\-_]{20,}$")


def shannon_entropy(text: str) -> float:
    """Shannon entropy of a string. Higher = more random = more likely a secret."""
    if not text:
        return 0.0
    freq: dict[str, int] = {}
    for c in text:
        freq[c] = freq.get(c, 0) + 1
    length = len(text)
    return -sum((count / length) * math.log2(count / length) for count in freq.values())


def is_high_entropy_string(
    token: str, threshold: float = 4.5, min_length: int = 20
) -> bool:
    """Return True if token looks like a high-entropy secret."""
    if len(token) < min_length:
        return False
    # Only test strings that look like encoded data
    if not (_B64_CHARS.match(token) or _HEX_CHARS.match(token) or _ALPHANUM.match(token)):
        return False
    return shannon_entropy(token) >= threshold


def extract_tokens(line: str) -> list[str]:
    """Extract potential secret tokens from a line of text."""
    raw = re.split(r'[\s=:"\'`,;{}()\[\]\\]', line)
    return [t for t in raw if len(t) >= 20]
