import logging
from typing import Dict

from GramAddict.core.llm_provider import query_llm

logger = logging.getLogger(__name__)


class LLMWriter:
    """
    The Creative Engine — Content Generation for Interactions.

    Generates high-fidelity, persona-aligned comments and messages.
    Replaces legacy static 'comment_list' with dynamic, contextual resonance.
    """

    def __init__(self, username: str, persona_interests: list[str], configs):
        self.username = username
        self.persona_interests = persona_interests
        self.configs = configs
        self.args = getattr(configs, "args", None)

    def generate_comment(self, post_data: Dict) -> str:
        """
        Generates a human-like comment based on post data and persona interests.
        """
        if not post_data:
            logger.warning("✍️ [Writer] No post data provided. Using generic fallback.")
            return "Cool!"

        caption = post_data.get("caption", "")
        description = post_data.get("description", "")
        target_username = post_data.get("username", "the user")

        # Build context for the LLM
        context = f"Post by @{target_username}\n"
        if caption:
            context += f"Caption: {caption}\n"
        if description:
            context += f"Visual Description: {description}\n"

        interests_str = ", ".join(self.persona_interests) if self.persona_interests else "general interesting things"

        prompt = (
            f"You are an Instagram user interested in: {interests_str}.\n"
            f"You want to leave a brief, friendly, and authentic comment on the following post:\n\n"
            f"{context}\n"
            f"INSTRUCTIONS:\n"
            f"1. Keep it under 10 words.\n"
            f"2. Be casual and human. Avoid overly formal language or sounding like a bot.\n"
            f"3. Do NOT use more than one emoji.\n"
            f"4. Do NOT use hashtags.\n"
            f"5. Focus on something specific in the post if possible.\n"
            f"6. Reply with ONLY the comment text."
        )

        model = getattr(self.args, "ai_writer_model", getattr(self.args, "ai_model"))
        url = getattr(
            self.args, "ai_writer_url", getattr(self.args, "ai_model_url")
        )

        logger.info(f"✍️ [Writer] Generating comment for @{target_username} using {model}...")

        try:
            response_dict = query_llm(
                url=url,
                model=model,
                prompt=prompt,
                system="You are a friendly Instagram user. You write short, authentic comments.",
                format_json=False,
                timeout=60,
                temperature=0.7,  # Add some variety to avoid 'the to the' loops
            )

            if response_dict and "response" in response_dict:
                comment = response_dict["response"].strip().strip('"')
                # Basic cleaning to remove LLM artifacts
                comment = comment.split("\n")[0]  # Take only first line
                if not comment:
                    return "Nice!"
                return comment

        except Exception as e:
            logger.error(f"✍️ [Writer] Failed to generate comment: {e}")

        return "Great post! 🔥"
