"""A2: AI Autonomy — tool streak analysis between user messages."""

from .base import BaseAnalyzer


class AutonomyAnalyzer(BaseAnalyzer):
    name = "a02_autonomy"

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

        for session in self.iter_sessions(sessions_df):
            sid = session["id"]
            msgs = self.get_session_messages(messages_df, sid)
            if msgs.empty:
                continue

            tool_call_count = 0
            user_count = 0
            assistant_count = 0
            streaks = []
            current_streak = 0

            for _, m in msgs.iterrows():
                mt = m["msg_type"]
                if mt == "tool_call":
                    tool_call_count += 1
                    current_streak += 1
                elif mt == "assistant":
                    assistant_count += 1
                elif mt == "user":
                    user_count += 1
                    if current_streak > 0:
                        streaks.append(current_streak)
                    current_streak = 0

            if current_streak > 0:
                streaks.append(current_streak)

            max_streak = max(streaks) if streaks else 0
            avg_streak = round(sum(streaks) / len(streaks), 2) if streaks else 0.0
            autonomous_segments = sum(1 for s in streaks if s >= 5)
            tool_calls_per_user = round(tool_call_count / user_count, 2) if user_count > 0 else 0.0
            denom = tool_call_count + assistant_count
            intervention_rate = round(user_count / denom, 4) if denom > 0 else 0.0

            per_session.append({
                "session_id": sid,
                "tool_calls_per_user_msg": tool_calls_per_user,
                "max_tool_streak": max_streak,
                "avg_tool_streak": avg_streak,
                "autonomous_segments": autonomous_segments,
                "user_intervention_rate": intervention_rate,
            })

        streaks_all = [s["max_tool_streak"] for s in per_session if s["max_tool_streak"] > 0]
        return {
            "global_max_streak": max(streaks_all) if streaks_all else 0,
            "sessions_with_tools": sum(1 for s in per_session if s["max_tool_streak"] > 0),
            "total_sessions": len(per_session),
            "per_session": per_session,
        }
