"""GameGrip Safety API — Conversation Store (Phase 2)

Lightweight in-memory conversation tracking with risk trend analysis.
Replace with Redis / PostgreSQL in production.
"""

from collections import defaultdict, deque
from typing import Dict, List, Optional
from datetime import datetime
from uuid import uuid4
from models import MessageRecord, ConversationHistoryResponse
from config import Decision, Platform


class ConversationStore:
    def __init__(self, max_history: int = 10):
        self.max_history = max_history
        # conversation_id -> deque of MessageRecord
        self._conversations: Dict[str, deque] = defaultdict(lambda: deque(maxlen=max_history))
        # user_id -> list of conversation_ids
        self._user_conversations: Dict[str, List[str]] = defaultdict(list)

    def add_message(self, user_id: str, conversation_id: str, text: Optional[str],
                    risk_score: int, decision: Decision, platform: Platform) -> MessageRecord:
        if not conversation_id:
            conversation_id = f"conv_{uuid4().hex[:8]}"
        if not user_id:
            user_id = f"user_{uuid4().hex[:8]}"

        record = MessageRecord(
            message_id=f"msg_{uuid4().hex[:12]}",
            user_id=user_id,
            conversation_id=conversation_id,
            text=text[:200] if text else None,  # truncate for storage
            timestamp=datetime.utcnow(),
            risk_score=risk_score,
            decision=decision,
            platform=platform,
        )

        self._conversations[conversation_id].append(record)
        if conversation_id not in self._user_conversations[user_id]:
            self._user_conversations[user_id].append(conversation_id)

        return record

    def get_conversation(self, conversation_id: str) -> List[MessageRecord]:
        return list(self._conversations.get(conversation_id, []))

    def get_user_conversations(self, user_id: str) -> List[str]:
        return self._user_conversations.get(user_id, [])

    def get_conversation_summary(self, conversation_id: str) -> Optional[ConversationHistoryResponse]:
        messages = self.get_conversation(conversation_id)
        if not messages:
            return None

        risks = [m.risk_score for m in messages]
        avg_risk = sum(risks) / len(risks)
        alerts = sum(1 for m in messages if m.decision in (Decision.BLOCK, Decision.REVIEW))

        # Trend: compare first half avg vs second half avg
        mid = len(risks) // 2
        first_half = sum(risks[:mid]) / max(mid, 1)
        second_half = sum(risks[mid:]) / max(len(risks) - mid, 1)

        if second_half > first_half * 1.2:
            trend = "rising"
        elif second_half < first_half * 0.8:
            trend = "falling"
        else:
            trend = "stable"

        return ConversationHistoryResponse(
            conversation_id=conversation_id,
            messages=messages,
            user_risk_trend=trend,
            average_risk=round(avg_risk, 2),
            alert_count=alerts,
        )

    def get_user_risk_score(self, user_id: str) -> float:
        """Compute aggregate risk score for a user across all conversations."""
        conv_ids = self._user_conversations.get(user_id, [])
        all_risks = []
        for cid in conv_ids:
            for msg in self._conversations.get(cid, []):
                all_risks.append(msg.risk_score)
        if not all_risks:
            return 0.0
        return sum(all_risks) / len(all_risks)


# Global singleton (use dependency injection in production)
conversation_store = ConversationStore(max_history=10)
