"""Normalize profile analysis structures for consistent access."""
from typing import Any, Dict, List


def _extract_from_list(items: Any, key: str) -> str:
    if not isinstance(items, list):
        return ""
    prefix = f"{key}:"
    for item in items:
        text = str(item)
        if text.lower().startswith(prefix):
            return text.split(":", 1)[1].strip()
    return ""


def _extract_list_from_list(items: Any, key: str) -> List[str]:
    value = _extract_from_list(items, key)
    if not value:
        return []
    return [part.strip() for part in value.split(",") if part.strip()]


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


def normalize_profile_analysis(profile_analysis: Dict[str, Any]) -> Dict[str, Any]:
    """Ensure nested fields are dicts with expected keys to avoid crashes."""
    if not isinstance(profile_analysis, dict):
        return {}

    normalized = dict(profile_analysis)

    visual = profile_analysis.get("visual_patterns", {})
    content_strategy = profile_analysis.get("content_strategy", {})
    structure_templates = profile_analysis.get("structure_templates", {})

    if isinstance(visual, list):
        normalized["visual_patterns"] = {
            "unicode_formatting": _extract_from_list(visual, "unicode_formatting"),
            "structure_preferences": _extract_from_list(visual, "structure_preferences"),
            "emoji_usage": {
                "placement": _extract_from_list(visual, "emoji_usage"),
                "frequency": _extract_from_list(visual, "emoji_usage"),
                "emojis": []
            }
        }
    else:
        normalized["visual_patterns"] = _ensure_dict(visual)

    if isinstance(content_strategy, list):
        normalized["content_strategy"] = {
            "cta_style": _extract_from_list(content_strategy, "cta_style"),
            "hook_patterns": _extract_from_list(content_strategy, "hook_patterns"),
            "post_structure": _extract_from_list(content_strategy, "post_structure"),
            "storytelling_approach": _extract_from_list(content_strategy, "storytelling_approach"),
        }
    else:
        normalized["content_strategy"] = _ensure_dict(content_strategy)

    if isinstance(structure_templates, list):
        normalized["structure_templates"] = {
            "primary_structure": _extract_from_list(structure_templates, "primary_structure"),
            "template_examples": _extract_list_from_list(structure_templates, "template_examples"),
            "paragraph_transitions": _extract_list_from_list(structure_templates, "paragraph_transitions"),
            "typical_sentence_starters": _extract_list_from_list(structure_templates, "typical_sentence_starters"),
        }
    else:
        normalized["structure_templates"] = _ensure_dict(structure_templates)

    return normalized
