"""A6: Detect when AI asks real clarification questions (not sign-off pleasantries)."""

from .base import BaseAnalyzer

REAL_CLARIFICATION_PATTERNS = [
    "would you like me to", "do you want me to", "should i ",
    "could you clarify", "which one", "before i proceed", "would you prefer", "do you want to",
]
SIGNOFF_PATTERNS = ["let me know", "feel free to", "if you have any"]


class AIClarificationAnalyzer(BaseAnalyzer):
    name = "a06_ai_clarification"

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

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

            clarification_count = 0
            positions = []
            total_msgs = len(msgs)

            for i, (_, m) in enumerate(msgs.iterrows()):
                content = m.get("content")
                if m["msg_type"] != "assistant" or not isinstance(content, str) or not content:
                    continue
                c_lower = content.lower()

                is_real = any(pat in c_lower for pat in REAL_CLARIFICATION_PATTERNS)
                is_signoff = any(pat in c_lower for pat in SIGNOFF_PATTERNS) and not is_real

                if is_real and not is_signoff:
                    clarification_count += 1
                    pct = i / max(total_msgs, 1)
                    if pct <= 0.2:
                        positions.append("early")
                    elif pct <= 0.66:
                        positions.append("mid")
                    else:
                        positions.append("late")

            position = max(set(positions), key=positions.count) if positions else None

            if clarification_count > 0:
                sessions_with += 1
            total_clarifications += clarification_count

            per_session.append({
                "session_id": sid,
                "ai_asked_clarification": clarification_count > 0,
                "clarification_count": clarification_count,
                "clarification_position": position,
            })

        return {
            "total_clarifications": total_clarifications,
            "sessions_with_clarification": sessions_with,
            "total_sessions": len(per_session),
            "per_session": per_session,
        }
