"""
{{ display_name }} - Analyze node.

This module handles sentiment and topic analysis using LLM.
"""

import json

from torivers_sdk.tools import LLMClient, LLMMessage

from state import {{ class_name }}State

{% raw %}
ANALYZE_PROMPT = """Analyze the following content for sentiment and topics.

Content:
{content}

Return a JSON object with:
{{
  "sentiment": {{
    "overall": "positive|negative|neutral|mixed",
    "confidence": 0.0-1.0,
    "aspects": [
      {{"aspect": "...", "sentiment": "...", "confidence": 0.0-1.0}}
    ]
  }},
  "topics": ["topic1", "topic2", ...]
}}

Return only valid JSON, no additional text."""
{% endraw %}


async def analyze(state: {{ class_name }}State) -> dict:
    """Perform sentiment and topic analysis.

    Args:
        state: Current analysis state.

    Returns:
        Dictionary with state updates including sentiment and topics.
    """
    context = state["context"]
    input_data = state["input_data"]

    content = input_data.get("content", "")
    context.log_progress("Analyzing", "Performing sentiment and topic analysis...")

    llm = LLMClient.get_default()
    response = await llm.chat(
        messages=[
            LLMMessage(
                role="system",
                content="You are an expert NLP analyst. Return only valid JSON.",
            ),
            LLMMessage(
                role="user",
                content=ANALYZE_PROMPT.format(content=content),
            ),
        ],
    )

    # Parse JSON response
    try:
        analysis = json.loads(response.content)
        sentiment = analysis.get("sentiment", {})
        topics = analysis.get("topics", [])
    except json.JSONDecodeError:
        sentiment = {"overall": "unknown", "confidence": 0.0}
        topics = []

    total_tokens = state.get("total_tokens_used", 0) + response.tokens_used
    context.log_success("Analysis complete", f"Found {len(topics)} topics")

    return {
        "current_step": "analyzed",
        "sentiment": sentiment,
        "topics": topics,
        "total_tokens_used": total_tokens,
        "metadata": {
            "analysis_tokens": response.tokens_used,
        },
    }
