"""A10: Error detection from tool output — shell errors, cascades, user rescue."""

from .base import BaseAnalyzer
from .helpers import is_shell_error


class ErrorDetectionAnalyzer(BaseAnalyzer):
    name = "a10_error_detection"

    def analyze(self, sessions_df, messages_df, tool_calls_df, tool_results_df, token_usage_df) -> dict:
        per_session = []
        total_shell_errors = 0

        for session in self.iter_sessions(sessions_df):
            sid = session["id"]
            stream = self.build_message_stream(messages_df, tool_calls_df, tool_results_df, sid)
            if not stream:
                continue

            shell_error_count = 0
            current_error_streak = 0
            max_error_streak = 0
            error_cascade_count = 0
            in_cascade = False
            error_then_rescue = False
            cascade_active = False

            for m in stream:
                if m["msg_type"] == "tool_result":
                    output = m.get("result_output") or ""
                    if is_shell_error(output):
                        shell_error_count += 1
                        current_error_streak += 1
                        max_error_streak = max(max_error_streak, current_error_streak)
                        if current_error_streak >= 3 and not in_cascade:
                            error_cascade_count += 1
                            in_cascade = True
                            cascade_active = True
                    else:
                        current_error_streak = 0
                        in_cascade = False
                elif m["msg_type"] == "user":
                    if cascade_active:
                        error_then_rescue = True
                        cascade_active = False
                    current_error_streak = 0
                    in_cascade = False

            total_shell_errors += shell_error_count

            per_session.append({
                "session_id": sid,
                "shell_error_count": shell_error_count,
                "consecutive_shell_errors": max_error_streak,
                "error_cascade_count": error_cascade_count,
                "error_then_user_rescue": error_then_rescue,
            })

        return {
            "total_shell_errors": total_shell_errors,
            "sessions_with_errors": sum(1 for s in per_session if s["shell_error_count"] > 0),
            "sessions_with_cascades": sum(1 for s in per_session if s["error_cascade_count"] > 0),
            "total_sessions": len(per_session),
            "per_session": per_session,
        }
