"""
Voice Personas - Format OpenContext persona for prompt injection.

ABOUTME: Formats the dynamically-generated voice_persona from OpenContext
ABOUTME: No hardcoded personas - all personas generated per-company by OpenContext

The voice_persona is generated by OpenContext based on actual company analysis,
ensuring consistent voice across all content for that company.
"""

from typing import Dict, Any, Optional
import logging

logger = logging.getLogger(__name__)


def format_voice_persona(voice_persona: Dict[str, Any]) -> str:
    """
    Format a voice persona from OpenContext into prompt-ready text.

    Args:
        voice_persona: Voice persona dict from OpenContext API response

    Returns:
        Formatted string for injection into prompts
    """
    if not voice_persona:
        logger.debug("No voice_persona provided")
        return ""

    lines = []

    # Add emphasis header to make voice persona stand out
    lines.append("=" * 60)
    lines.append("CRITICAL: VOICE PERSONA - FOLLOW THIS EXACTLY")
    lines.append("=" * 60)
    lines.append("")
    lines.append("VOICE PERSONA (Tailored to Target Audience)")

    # ICP Profile - who we're writing for
    if voice_persona.get("icp_profile"):
        lines.append(f"\nTARGET READER (ICP): {voice_persona['icp_profile']}")

    if voice_persona.get("voice_style"):
        lines.append(f"\nCore Voice: {voice_persona['voice_style']}")

    # Language style preferences
    lang_style = voice_persona.get("language_style", {})
    if lang_style:
        lines.append("\n\nLANGUAGE STYLE FOR THIS AUDIENCE:")
        if lang_style.get("formality"):
            lines.append(f"- Formality: {lang_style['formality']}")
        if lang_style.get("complexity"):
            lines.append(f"- Vocabulary Complexity: {lang_style['complexity']}")
        if lang_style.get("sentence_length"):
            lines.append(f"- Sentence Style: {lang_style['sentence_length']}")
        if lang_style.get("perspective"):
            lines.append(f"- Reader Perspective: {lang_style['perspective']}")

    if voice_persona.get("sentence_patterns"):
        lines.append("\n\nWRITING PATTERNS:")
        for pattern in voice_persona["sentence_patterns"]:
            lines.append(f"- {pattern}")

    if voice_persona.get("vocabulary_level"):
        lines.append(f"\n\nVocabulary Level: {voice_persona['vocabulary_level']}")

    if voice_persona.get("authority_signals"):
        lines.append("\n\nWHAT MAKES THIS AUDIENCE TRUST CONTENT:")
        for signal in voice_persona["authority_signals"]:
            lines.append(f"- {signal}")

    if voice_persona.get("do_list"):
        lines.append("\n\nDO (Resonates with this ICP):")
        for item in voice_persona["do_list"]:
            lines.append(f"- {item}")

    if voice_persona.get("dont_list"):
        lines.append("\n\nDON'T (Turns off this ICP):")
        for item in voice_persona["dont_list"]:
            lines.append(f"- {item}")

    if voice_persona.get("example_phrases"):
        lines.append("\n\nTONE MARKERS (phrases that resonate with this audience):")
        for phrase in voice_persona["example_phrases"]:
            lines.append(f'- "{phrase}"')

    if voice_persona.get("opening_styles"):
        lines.append("\n\nSECTION OPENERS THAT ENGAGE THIS AUDIENCE:")
        for style in voice_persona["opening_styles"]:
            lines.append(f"- {style}")

    # Add closing reminder
    lines.append("")
    lines.append("=" * 60)
    lines.append("REMINDER: Every sentence should sound like this persona wrote it.")
    lines.append("=" * 60)

    return "\n".join(lines)


def get_voice_persona_section(company_data: Dict[str, Any]) -> str:
    """
    Get the voice persona prompt section from company data.

    This extracts the voice_persona from OpenContext response and formats it.

    Args:
        company_data: Full company data dict (from OpenContext or Stage 0)

    Returns:
        Formatted persona prompt section, or empty string if no persona
    """
    voice_persona = company_data.get("voice_persona")

    if not voice_persona:
        logger.debug("No voice_persona in company_data")
        return ""

    return format_voice_persona(voice_persona)
