"""C2: Team-Level Weekly Trends.

Aggregates all sessions by ISO week for team-level trend analysis.
Uses pricing.py for cost calculations — does NOT reimplement cost logic.
"""

import os
import sys
from collections import Counter

import pandas as pd

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from .base import BaseAnalyzer
from .helpers import detect_interrupt_pattern, EDIT_TOOLS
from utils.pricing import calc_cost


class TeamTrends(BaseAnalyzer):
    name = "c02_team_trends"

    def analyze(self, sessions_df, messages_df, tool_calls_df, tool_results_df, token_usage_df) -> dict:
        if sessions_df.empty:
            return {"weeks": [], "total_sessions": 0}

        # Add ISO week column from first_seen
        sessions = sessions_df.copy()
        sessions["_start"] = pd.to_datetime(sessions["first_seen"])
        iso = sessions["_start"].dt.isocalendar()
        sessions["_iso_week"] = iso.year.astype(str) + "-W" + iso.week.astype(str).str.zfill(2)

        # Pre-compute per-session flags
        session_flags = {}
        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:
                session_flags[sid] = {"has_edit": False, "interrupt_count": 0}
                continue

            tool_msgs = [m for m in stream if m.get("tool_name")]
            has_edit = any(m.get("tool_name") in EDIT_TOOLS for m in tool_msgs)

            interrupt_count = sum(
                1 for m in stream
                if m["msg_type"] == "tool_result"
                and detect_interrupt_pattern(m.get("result_output") or "") is not None
            )

            session_flags[sid] = {
                "has_edit": has_edit,
                "interrupt_count": interrupt_count,
            }

        # Aggregate by week
        weekly = []
        for iso_week, group in sessions.groupby("_iso_week"):
            week_sids = group["id"].tolist()
            n = len(week_sids)

            edit_sessions = sum(1 for s in week_sids if session_flags.get(s, {}).get("has_edit", False))
            interrupt_sessions = sum(1 for s in week_sids if session_flags.get(s, {}).get("interrupt_count", 0) > 0)

            # Cost from token_usage_df
            week_cost = 0.0
            if not token_usage_df.empty:
                week_tokens = token_usage_df[token_usage_df["session_id"].isin(week_sids)]
                for _, row in week_tokens.iterrows():
                    model = row.get("model") or ""
                    week_cost += calc_cost(
                        model,
                        input_tokens=row.get("input_tokens", 0) or 0,
                        output_tokens=row.get("output_tokens", 0) or 0,
                        cached_tokens=row.get("cached_tokens", 0) or 0,
                    )

            # Source distribution
            source_dist = dict(Counter(group["source"].dropna())) if "source" in group.columns else {}

            weekly.append({
                "iso_week": iso_week,
                "sessions_count": n,
                "edit_sessions_pct": round(edit_sessions / max(n, 1), 3),
                "interrupt_rate": round(interrupt_sessions / max(n, 1), 3),
                "avg_session_cost": round(week_cost / max(n, 1), 4),
                "total_cost": round(week_cost, 2),
                "source_distribution": source_dist,
            })

        weekly.sort(key=lambda x: x["iso_week"])
        print(f"  [c02] Generated trends for {len(weekly)} weeks, {len(sessions)} sessions")
        return {"total_sessions": len(sessions), "weeks": weekly}
