"""A5: Undo/Revert Detection — user undo requests, git reverts, AI self-corrections."""

from .base import BaseAnalyzer
from .helpers import clean_user_content, SHELL_TOOLS

UNDO_PATTERNS = ["undo", "revert this", "revert that", "revert the",
                  "roll back", "go back to", "put it back"]
GIT_REVERT_PATTERNS = ["git checkout --", "git reset", "git restore", "git stash"]
AI_SELF_CORRECTION_PATTERNS = ["i apologize", "my mistake", "let me fix that", "that was incorrect"]


class UndoRevertAnalyzer(BaseAnalyzer):
    name = "a05_undo_revert"

    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"]
            source = session.get("source") or ""
            stream = self.build_message_stream(messages_df, tool_calls_df, tool_results_df, sid)
            if not stream:
                continue

            undo_count = 0
            git_revert = False
            ai_correction_count = 0

            for m in stream:
                raw_content = m.get("content")
                if m["msg_type"] == "user" and isinstance(raw_content, str) and raw_content:
                    cleaned = clean_user_content(raw_content, source)
                    if not cleaned or len(cleaned) < 5:
                        continue
                    c_lower = cleaned.lower()
                    for kw in UNDO_PATTERNS:
                        if kw in c_lower:
                            undo_count += 1
                            break

                if m["msg_type"] == "tool_call" and m.get("tool_name") in SHELL_TOOLS:
                    ti = m.get("tool_input")
                    ti_str = ""
                    if isinstance(ti, dict):
                        ti_str = (ti.get("command") or "").lower()
                    elif isinstance(ti, str):
                        ti_str = ti.lower()
                    for gp in GIT_REVERT_PATTERNS:
                        if gp in ti_str:
                            git_revert = True
                            break

                content = m.get("content")
                if m["msg_type"] == "assistant" and isinstance(content, str) and content:
                    c_lower = content.lower()
                    for pat in AI_SELF_CORRECTION_PATTERNS:
                        if pat in c_lower:
                            ai_correction_count += 1
                            break

            per_session.append({
                "session_id": sid,
                "user_requested_undo": undo_count > 0,
                "undo_request_count": undo_count,
                "git_revert_in_session": git_revert,
                "ai_self_corrected": ai_correction_count > 0,
                "ai_self_correction_count": ai_correction_count,
            })

        return {
            "sessions_with_undo": sum(1 for s in per_session if s["user_requested_undo"]),
            "sessions_with_git_revert": sum(1 for s in per_session if s["git_revert_in_session"]),
            "sessions_with_ai_correction": sum(1 for s in per_session if s["ai_self_corrected"]),
            "total_sessions": len(per_session),
            "per_session": per_session,
        }
