"""A9: Tool usage profile — counts by category, ratios, dominant category."""

from .base import BaseAnalyzer
from .helpers import categorize_tool


class ToolProfileAnalyzer(BaseAnalyzer):
    name = "a09_tool_profile"

    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"]
            tc = self.get_session_tool_calls(tool_calls_df, sid)

            counts = {"explore": 0, "edit": 0, "shell": 0, "plan": 0,
                       "delegation": 0, "web": 0, "mcp": 0, "other": 0}
            unique_tools = set()

            if not tc.empty:
                for _, row in tc.iterrows():
                    tn = row.get("tool_name") or ""
                    if not tn:
                        continue
                    unique_tools.add(tn)
                    cat = categorize_tool(tn)
                    counts[cat] = counts.get(cat, 0) + 1

            explore_edit_ratio = round(counts["explore"] / max(counts["edit"], 1), 2)
            main_cats = {k: v for k, v in counts.items() if k != "other"}
            dominant = max(main_cats, key=main_cats.get) if any(main_cats.values()) else None

            per_session.append({
                "session_id": sid,
                "explore_count": counts["explore"],
                "edit_count": counts["edit"],
                "shell_count": counts["shell"],
                "plan_count": counts["plan"],
                "delegation_count": counts["delegation"],
                "web_count": counts["web"],
                "mcp_count": counts["mcp"],
                "explore_edit_ratio": explore_edit_ratio,
                "unique_tools_used": len(unique_tools),
                "dominant_tool_category": dominant,
            })

        return {"total_sessions": len(per_session), "per_session": per_session}
