"""Readability checker for German text."""
from typing import Dict, Any, List
from loguru import logger

from src.agents.base import BaseAgent


class ReadabilityChecker(BaseAgent):
    """Agent for checking text readability."""

    def __init__(self):
        """Initialize readability checker."""
        super().__init__("ReadabilityChecker")
        self.textstat_available = False
        self._initialize_textstat()

    def _initialize_textstat(self):
        """Initialize textstat library."""
        try:
            import textstat
            self.textstat = textstat
            # Set language to German
            textstat.set_lang("de")
            self.textstat_available = True
            logger.info("Textstat initialized successfully")
        except Exception as e:
            logger.error(f"Failed to initialize textstat: {e}")
            self.textstat = None

    async def process(
        self,
        text: str,
        target_grade: float = 10.0,
        target_flesch: float = 60.0,
        max_sentence_length: int = 20
    ) -> Dict[str, Any]:
        """
        Analyze text readability.

        Args:
            text: Text to analyze
            target_grade: Target grade level (Wiener Sachtextformel)
            target_flesch: Target Flesch reading ease score
            max_sentence_length: Maximum average sentence length

        Returns:
            Readability analysis results
        """
        if not self.textstat_available:
            logger.warning("Textstat not available, skipping readability check")
            return {
                "available": False,
                "passed": True,
                "score": 0.0
            }

        logger.info("Analyzing text readability")

        try:
            # Calculate various readability metrics

            # Wiener Sachtextformel (German readability)
            # Scale: 4 (very easy) to 15 (very difficult)
            # Optimal for LinkedIn: 8-12 (general audience)
            try:
                wstf = self.textstat.wiener_sachtextformel(text, variant=1)
            except:
                wstf = None

            # Flesch Reading Ease (adapted for German)
            # Scale: 0-100 (higher = easier)
            # Optimal for LinkedIn: 60-70
            try:
                flesch = self.textstat.flesch_reading_ease(text)
            except:
                flesch = None

            # Average sentence length
            avg_sentence_length = self.textstat.avg_sentence_length(text)

            # Sentence count
            sentence_count = self.textstat.sentence_count(text)

            # Word count
            word_count = self.textstat.lexicon_count(text, removepunct=True)

            # Average syllables per word
            avg_syllables = self.textstat.avg_syllables_per_word(text)

            # Difficult words (more than 3 syllables)
            difficult_words = self.textstat.difficult_words(text)

            # Determine if text passes readability requirements
            passed = True
            issues = []

            if wstf is not None and wstf > target_grade:
                passed = False
                issues.append(f"Zu komplex (WSTF: {wstf:.1f}, Ziel: ≤{target_grade})")

            if flesch is not None and flesch < target_flesch:
                passed = False
                issues.append(f"Schwer lesbar (Flesch: {flesch:.1f}, Ziel: ≥{target_flesch})")

            if avg_sentence_length > max_sentence_length:
                passed = False
                issues.append(f"Sätze zu lang (Ø {avg_sentence_length:.1f} Wörter, Ziel: ≤{max_sentence_length})")

            # Get verdict
            verdict = self._get_verdict(wstf, flesch, avg_sentence_length, target_grade, target_flesch, max_sentence_length)

            result = {
                "available": True,
                "passed": passed,
                "issues": issues,
                "verdict": verdict,
                "metrics": {
                    "wiener_sachtextformel": wstf,
                    "flesch_reading_ease": flesch,
                    "avg_sentence_length": avg_sentence_length,
                    "sentence_count": sentence_count,
                    "word_count": word_count,
                    "avg_syllables_per_word": avg_syllables,
                    "difficult_words": difficult_words,
                    "difficult_words_percentage": (difficult_words / word_count * 100) if word_count > 0 else 0
                },
                "targets": {
                    "target_grade": target_grade,
                    "target_flesch": target_flesch,
                    "max_sentence_length": max_sentence_length
                }
            }

            if passed:
                logger.info(f"✅ Readability check passed")
            else:
                logger.warning(f"⚠️ Readability issues: {', '.join(issues)}")

            return result

        except Exception as e:
            logger.error(f"Readability check failed: {e}")
            return {
                "available": False,
                "passed": True,
                "error": str(e)
            }

    def _get_verdict(
        self,
        wstf: float,
        flesch: float,
        avg_sent_len: float,
        target_grade: float,
        target_flesch: float,
        max_sent_len: int
    ) -> str:
        """Get human-readable verdict."""
        if wstf is None and flesch is None:
            return "⚠️ Keine Metrik verfügbar"

        issues = []

        # WSTF check
        if wstf is not None:
            if wstf <= 8:
                issues.append("✅ Sehr leicht lesbar")
            elif wstf <= target_grade:
                issues.append("✅ Gut lesbar")
            elif wstf <= target_grade + 2:
                issues.append("⚠️ Etwas komplex")
            else:
                issues.append("❌ Zu komplex - vereinfachen!")

        # Flesch check
        if flesch is not None:
            if flesch >= 70:
                issues.append("✅ Leicht verständlich")
            elif flesch >= target_flesch:
                issues.append("✅ Gut verständlich")
            elif flesch >= 50:
                issues.append("⚠️ Mittelschwer")
            else:
                issues.append("❌ Schwer verständlich")

        # Sentence length check
        if avg_sent_len > max_sent_len + 5:
            issues.append("❌ Sätze zu lang")
        elif avg_sent_len > max_sent_len:
            issues.append("⚠️ Sätze etwas lang")
        else:
            issues.append("✅ Gute Satzlänge")

        return " | ".join(issues)

    def get_summary(self, check_result: Dict[str, Any]) -> str:
        """
        Get human-readable summary of readability check.

        Args:
            check_result: Result from process()

        Returns:
            Summary string
        """
        if not check_result.get("available"):
            return "⚠️ Lesbarkeits-Check nicht verfügbar"

        metrics = check_result.get("metrics", {})
        wstf = metrics.get("wiener_sachtextformel")
        flesch = metrics.get("flesch_reading_ease")
        avg_len = metrics.get("avg_sentence_length")

        summary = "📊 Lesbarkeit: "

        parts = []
        if wstf is not None:
            parts.append(f"WSTF={wstf:.1f}")
        if flesch is not None:
            parts.append(f"Flesch={flesch:.1f}")
        if avg_len is not None:
            parts.append(f"Ø Satzlänge={avg_len:.1f}")

        summary += ", ".join(parts)

        if check_result.get("passed"):
            summary += " ✅"
        else:
            summary += f" ⚠️ ({', '.join(check_result.get('issues', []))})"

        return summary

    def get_improvement_suggestions(self, check_result: Dict[str, Any]) -> List[str]:
        """
        Get specific improvement suggestions based on readability analysis.

        Args:
            check_result: Result from process()

        Returns:
            List of improvement suggestions
        """
        if not check_result.get("available") or check_result.get("passed"):
            return []

        suggestions = []
        metrics = check_result.get("metrics", {})

        # Sentence length suggestions
        avg_len = metrics.get("avg_sentence_length", 0)
        if avg_len > 25:
            suggestions.append("Teile lange Sätze auf - maximal 20-25 Wörter pro Satz")
        elif avg_len > 20:
            suggestions.append("Kürze einige Sätze für besseren Lesefluss")

        # Complexity suggestions
        wstf = metrics.get("wiener_sachtextformel")
        if wstf and wstf > 12:
            suggestions.append("Vereinfache Sprache - weniger Fachbegriffe und Schachtelsätze")

        # Word choice suggestions
        difficult_pct = metrics.get("difficult_words_percentage", 0)
        if difficult_pct > 15:
            suggestions.append("Ersetze komplexe Wörter durch einfachere Alternativen")

        # Syllables suggestions
        avg_syllables = metrics.get("avg_syllables_per_word", 0)
        if avg_syllables > 2.0:
            suggestions.append("Nutze kürzere, prägnantere Wörter")

        return suggestions
