"""
Session Analytics
Tracks and analyzes conversational sessions.
"""
import uuid
import time
import sqlite3
from typing import Dict, Any, List
from collections import Counter
from .usage_tracker import UsageTracker

class SessionAnalytics:
    def __init__(self, tracker: UsageTracker):
        self.tracker = tracker
        self._current_session = None
        self._last_interaction_time = 0

    def current_session_id(self) -> str:
        now = time.time()
        # 30 min idle timeout
        if self._current_session is None or now - self._last_interaction_time > 1800:
            self._current_session = uuid.uuid4().hex[:12]
        self._last_interaction_time = now
        return self._current_session

    def session_duration(self, session_id: str) -> float:
        summary = self.tracker.session_summary(session_id)
        if not summary:
            return 0.0
        try:
            start = time.mktime(time.strptime(summary["start_time"], "%Y-%m-%dT%H:%M:%SZ"))
            end = time.mktime(time.strptime(summary["end_time"], "%Y-%m-%dT%H:%M:%SZ"))
            return (end - start) / 60.0
        except Exception:
            return 0.0

    def conversation_length(self, session_id: str) -> int:
        summary = self.tracker.session_summary(session_id)
        return summary.get("interactions", 0)

    def topic_tracking(self, session_id: str) -> List[str]:
        with sqlite3.connect(self.tracker.db_path) as conn:
            c = conn.cursor()
            c.execute('SELECT strategy, model FROM interactions WHERE session_id = ?', (session_id,))
            rows = c.fetchall()
            
            if not rows:
                return []
                
            strats = [r[0] for r in rows]
            models = [r[1] for r in rows]
            
            top_strat = Counter(strats).most_common(1)[0][0]
            top_model = Counter(models).most_common(1)[0][0]
            
            # Simple heuristic labels
            labels = []
            if top_strat == "code": labels.append("Coding")
            elif top_strat == "debate": labels.append("Evaluation")
            elif top_strat == "refine": labels.append("Drafting")
            elif top_strat == "fan_out": labels.append("Research")
            else: labels.append("General Chat")
            
            labels.append(f"Using {top_model}")
            return labels

    def resolution_rate(self, days: int = 30) -> float:
        sessions = self.tracker.get_sessions(days=days, limit=1000)
        if not sessions:
            return 0.0
            
        success_sessions = 0
        valid_sessions = 0
        
        with sqlite3.connect(self.tracker.db_path) as conn:
            c = conn.cursor()
            for s in sessions:
                sid = s["session_id"]
                if s["interaction_count"] > 1:
                    valid_sessions += 1
                    c.execute('SELECT status FROM interactions WHERE session_id = ? ORDER BY timestamp DESC LIMIT 1', (sid,))
                    last_status = c.fetchone()
                    if last_status and last_status[0] == 'success':
                        success_sessions += 1
                        
        return success_sessions / float(valid_sessions) if valid_sessions > 0 else 0.0

    def avg_session_length(self, days: int = 30) -> Dict[str, Any]:
        sessions = self.tracker.get_sessions(days=days, limit=1000)
        if not sessions:
            return {"avg_interactions": 0, "avg_duration_minutes": 0.0, "median_interactions": 0}
            
        interactions = [s["interaction_count"] for s in sessions]
        durations = [s["duration_minutes"] for s in sessions]
        
        avg_int = sum(interactions) / len(interactions)
        avg_dur = sum(durations) / len(durations)
        med_int = sorted(interactions)[len(interactions) // 2]
        
        return {
            "avg_interactions": avg_int,
            "avg_duration_minutes": avg_dur,
            "median_interactions": med_int
        }

    def longest_sessions(self, limit: int = 5) -> List[Dict[str, Any]]:
        sessions = self.tracker.get_sessions(days=30, limit=1000)
        sorted_sessions = sorted(sessions, key=lambda x: x["interaction_count"], reverse=True)
        top = sorted_sessions[:limit]
        
        res = []
        for s in top:
            summary = self.tracker.session_summary(s["session_id"])
            res.append({
                "session_id": s["session_id"],
                "interactions": s["interaction_count"],
                "duration_minutes": s["duration_minutes"],
                "models_used": summary.get("models_used", [])
            })
        return res

    def session_heatmap(self, days: int = 30) -> Dict[str, Dict[int, int]]:
        with sqlite3.connect(self.tracker.db_path) as conn:
            c = conn.cursor()
            cutoff = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - days * 86400))
            c.execute('''SELECT session_id, MIN(timestamp)
                         FROM interactions WHERE timestamp >= ?
                         GROUP BY session_id''', (cutoff,))
                         
            heatmap = {str(d): {h: 0 for h in range(24)} for d in range(7)}
            for r in c.fetchall():
                try:
                    t = time.strptime(r[1], "%Y-%m-%dT%H:%M:%SZ")
                    heatmap[str(t.tm_wday)][t.tm_hour] += 1
                except:
                    pass
            
            day_names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
            return {day_names[int(k)]: v for k, v in heatmap.items()}
