"""Generate a short insights summary using NVIDIA-hosted LLM."""
from __future__ import annotations

from typing import Any, Dict, Optional

from loguru import logger
from openai import OpenAI

from src.config import settings


def _build_prompt(post_insights: Dict[str, Any]) -> str:
    return (
        "Erstelle eine kurze, prägnante Zusammenfassung (2-4 Sätze) der wichtigsten "
        "Insights aus den folgenden LinkedIn-Post-Metriken. Fokus: Trends, auffällige "
        "Performance, was gut funktioniert.\n\n"
        f"Posts: {post_insights.get('total_posts')}\n"
        f"Ø Reaktionen/Post: {post_insights.get('avg_reactions')}\n"
        f"Ø Likes: {post_insights.get('avg_likes')}\n"
        f"Ø Comments: {post_insights.get('avg_comments')}\n"
        f"Ø Shares: {post_insights.get('avg_shares')}\n"
        f"Letzte 7 Tage Reaktionen: {post_insights.get('last_7_reactions')}\n"
        f"Trend vs Vorwoche (%): {post_insights.get('trend_pct')}\n"
        f"Bester Wochentag: {post_insights.get('best_weekday')}\n"
        f"Posting-Kadenz/Woche: {post_insights.get('cadence_per_week')}\n"
    )


def _is_summary_complete(text: str) -> bool:
    if not text:
        return False
    cleaned = text.strip()
    if len(cleaned) < 60:
        return False
    if cleaned[-1] not in ".!?":
        return False
    return True


def generate_insights_summary(post_insights: Dict[str, Any]) -> Optional[str]:
    """Generate a short summary for the insights page."""
    if not settings.nvidia_api_key:
        return None

    try:
        client = OpenAI(
            base_url="https://integrate.api.nvidia.com/v1",
            api_key=settings.nvidia_api_key,
        )

        completion = client.chat.completions.create(
            model="deepseek-ai/deepseek-v3.2",
            messages=[{"role": "user", "content": _build_prompt(post_insights)}],
            temperature=0.6,
            top_p=0.95,
            max_tokens=300,
        )

        content = None
        if completion and completion.choices:
            content = completion.choices[0].message.content
        if content:
            text = content.strip()
            if _is_summary_complete(text):
                return text

        # Retry once with stricter settings if output looks incomplete
        retry = client.chat.completions.create(
            model="deepseek-ai/deepseek-v3.2",
            messages=[{"role": "user", "content": _build_prompt(post_insights)}],
            temperature=0.4,
            top_p=0.9,
            max_tokens=220,
        )
        if retry and retry.choices:
            text = (retry.choices[0].message.content or "").strip()
            if _is_summary_complete(text):
                return text
        return None
    except Exception as e:
        logger.warning(f"Failed to generate insights summary: {e}")
        return None
