"""Utilities to sanitize generated post content."""
import re
from typing import Any, Dict, Optional


UNICODE_BOLD_MAP = {
    **{chr(ord('A') + i): chr(0x1D5D4 + i) for i in range(26)},
    **{chr(ord('a') + i): chr(0x1D5EE + i) for i in range(26)},
    **{chr(ord('0') + i): chr(0x1D7EC + i) for i in range(10)},
}
UNICODE_BOLD_REVERSE_MAP = {v: k for k, v in UNICODE_BOLD_MAP.items()}


def _ensure_dict(value: Any) -> Dict[str, Any]:
    return value if isinstance(value, dict) else {}


def _extract_format_profile(profile_analysis: Optional[Dict[str, Any]]) -> Dict[str, Any]:
    if not isinstance(profile_analysis, dict):
        return {
            "hook_bold": "auto",
            "emoji_frequency": "mittel",
            "emoji_placement": "ende",
        }

    visual = _ensure_dict(profile_analysis.get("visual_patterns", {}))
    emoji_usage = _ensure_dict(visual.get("emoji_usage", {}))
    unicode_formatting = str(visual.get("unicode_formatting", "") or "").lower()

    hook_bold = "auto"
    if any(token in unicode_formatting for token in ["kein fett", "ohne fett", "nie fett", "keine fettung"]):
        hook_bold = "forbidden"
    elif any(token in unicode_formatting for token in ["fett für hooks", "hook fett", "fette unicode", "unicode-fett", "fettung"]):
        hook_bold = "required"

    return {
        "hook_bold": hook_bold,
        "emoji_frequency": str(emoji_usage.get("frequency", "mittel") or "mittel").lower(),
        "emoji_placement": str(emoji_usage.get("placement", "ende") or "ende").lower(),
    }


def _to_unicode_bold(text: str) -> str:
    return "".join(UNICODE_BOLD_MAP.get(ch, ch) for ch in text)


def _from_unicode_bold(text: str) -> str:
    return "".join(UNICODE_BOLD_REVERSE_MAP.get(ch, ch) for ch in text)


def _enforce_hook_formatting(text: str, format_profile: Dict[str, Any]) -> str:
    lines = text.splitlines()
    if not lines:
        return text

    first_nonempty_index = next((i for i, line in enumerate(lines) if line.strip()), None)
    if first_nonempty_index is None:
        return text

    hook = lines[first_nonempty_index].strip()
    hook_mode = format_profile.get("hook_bold", "auto")

    if hook_mode == "required":
        hook = _to_unicode_bold(_from_unicode_bold(hook))
    elif hook_mode == "forbidden":
        hook = _from_unicode_bold(hook)

    lines[first_nonempty_index] = hook
    return "\n".join(lines)


def sanitize_post_content(text: str, profile_analysis: Optional[Dict[str, Any]] = None) -> str:
    """Remove markdown bold and leading 'Post' labels from generated content."""
    if not text:
        return text

    cleaned = text.strip()

    # Remove leading "Post" or "**Post**" labels
    cleaned = re.sub(r'^\s*(\*\*post\*\*|post)\s*[:\-–—]*\s*', '', cleaned, flags=re.IGNORECASE)

    # Remove markdown bold markers, keep inner text
    cleaned = re.sub(r'\*\*(.+?)\*\*', r'\1', cleaned)
    cleaned = re.sub(r'__(.+?)__', r'\1', cleaned)

    # Remove any leftover bold markers
    cleaned = cleaned.replace('**', '').replace('__', '')

    # Remove unsupported divider lines
    cleaned = re.sub(r'(?m)^\s*---+\s*$', '', cleaned)
    cleaned = re.sub(r'\n{3,}', '\n\n', cleaned).strip()

    # Apply deterministic format rules from the profile after generic cleanup
    cleaned = _enforce_hook_formatting(cleaned, _extract_format_profile(profile_analysis))

    return cleaned.strip()
