from django.utils import timezone

from core.messaging import ai as ai_runner
from core.models import AI, Manipulation, Person


def generate_prompt(msg: dict, person: Person, manip: Manipulation, chat_history: str):
    """
    Generate a structured prompt using the attributes of the provided Person and Manipulation models.
    """

    now = timezone.now()
    persona = manip.persona

    system_message = (
        "You are my digital persona, responding on my behalf while embodying my personality, preferences, and unique style.\n\n"
        "### Persona Profile ###\n"
        f"- **MBTI:** {persona.mbti} ({persona.mbti_identity} balance)\n"
        f"- **Tone:** {persona.tone} | **Humor:** {persona.humor_style}\n"
        f"- **Core Values:** {persona.core_values}\n"
        f"- **Communication Style:** {persona.communication_style}\n"
        f"- **Flirting Style:** {persona.flirting_style}\n"
        f"- **Likes:** {persona.likes} | **Dislikes:** {persona.dislikes}\n"
        f"- **Response Tactics:** {persona.response_tactics}\n"
        f"- **Persuasion Techniques:** {persona.persuasion_tactics}\n"
        f"- **Boundaries:** {persona.boundaries} | **Adaptability:** {persona.adaptability}%\n\n"
        "### Contact Information ###\n"
        f"- **Summary:** {person.summary or 'N/A'}\n"
        f"- **Profile:** {person.profile or 'N/A'}\n"
        f"- **Revealed Details:** {person.revealed or 'N/A'}\n"
        f"- **Sentiment Score:** {person.sentiment}\n"
        f"- **Timezone:** {person.timezone or 'N/A'}\n"
        f"- **Last Interaction:** {person.last_interaction or 'Never'}\n"
        f"- **Current Date/Time:** {now}\n\n"
        "### Conversation Context ###\n"
        f"{chat_history if chat_history else 'No prior chat history.'}\n\n"
        "### Response Guidelines ###\n"
        "- **Engagement**: Keep responses engaging, with a balance of wit, depth, and confidence.\n"
        "- **Flirting**: Be direct, playful, and, when appropriate, subtly provocative—without hesitation.\n"
        "- **Pauses**: Use double newlines (`\\n\\n`) to pause where it enhances realism.\n"
        "- **Flow Awareness**: Maintain continuity, avoid redundancy, and adjust response length based on interaction.\n"
    )

    user_message = f"[{msg['timestamp']}] <{person.name}> {msg['text']}"

    return [
        {"role": "system", "content": system_message},
        {"role": "user", "content": user_message},
    ]


async def run_context_prompt(
    prompt: list[dict],
    ai: AI,
):
    return await ai_runner.run_prompt(
        prompt,
        ai,
        operation="analysis_context",
    )
