"""
User Identity Helper
Xác định user identity từ request

Design:
- Có user_id:     Langfuse User ID = user_id,   metadata = {device_id: "xxx", is_authenticated: true}
- Không user_id:  Langfuse User ID = device_id, metadata = {device_id: "xxx", is_authenticated: false}
"""
from __future__ import annotations

import logging
from dataclasses import dataclass, field
from datetime import datetime

from fastapi import Request

logger = logging.getLogger(__name__)


@dataclass
class UserIdentity:
    """User identity với các thông tin cần thiết"""
    
    # ID chính dùng cho Langfuse, history, rate limit
    primary_id: str
    
    # Device ID (luôn có)
    device_id: str
    
    # User ID từ token (chỉ có khi đã login)
    user_id: str | None
    
    # Đã login hay chưa
    is_authenticated: bool
    
    @property
    def langfuse_user_id(self) -> str:
        """User ID cho Langfuse tracking"""
        return self.primary_id
    
    @property
    def langfuse_session_id(self) -> str:
        """Session ID cho Langfuse (theo device + ngày)"""
        today = datetime.now().strftime("%Y%m%d")
        return f"{self.device_id}-{today}"
    
    @property
    def langfuse_metadata(self) -> dict:
        """Metadata cho Langfuse"""
        return {
            "device_id": self.device_id,    
            "is_authenticated": self.is_authenticated,
        }
    
    @property
    def langfuse_tags(self) -> list[str]:
        """Tags cho Langfuse"""
        tags = ["chatbot", "production"]
        tags.append("customer" if self.is_authenticated else "guest")
        return tags
    
    @property
    def history_key(self) -> str:
        """
        Key để lưu/load chat history.
        - Guest (chưa login): device_id
        - User (đã login): user_id (customer_id từ Canifa)
        """
        if self.is_authenticated and self.user_id:
            return self.user_id
        return self.device_id
    
    @property
    def rate_limit_key(self) -> str:
        """
        Key cho rate limiting.
        - Guest (chưa login): device_id → limit 10
        - User (đã login): user_id → limit 100
        """
        if self.is_authenticated and self.user_id:
            return self.user_id
        return self.device_id


def get_user_identity(request: Request) -> UserIdentity:
    """
    Extract user identity từ request.
    
    Logic:
    - Có user_id (từ token) → primary_id = user_id
    - Không có → primary_id = device_id
    
    Args:
        request: FastAPI Request object
        
    Returns:
        UserIdentity object
    """
    # 1. Lấy device_id từ header (luôn có)
    device_id = request.headers.get("device_id", "")
    if not device_id:
        device_id = f"unknown_{request.client.host}" if request.client else "unknown"
    
    # 2. Lấy user_id từ token (middleware đã parse)
    user_id = None
    is_authenticated = False
     
    if hasattr(request.state, "user_id") and request.state.user_id:
        user_id = request.state.user_id
        is_authenticated = True
    
    # 3. Primary ID - LUÔN LUÔN LÀ device_id
    primary_id = device_id
    
    identity = UserIdentity(
        primary_id=primary_id,
        device_id=device_id,
        user_id=user_id,
        is_authenticated=is_authenticated,
    )
    
    logger.debug(
        f"UserIdentity: langfuse_user_id={identity.langfuse_user_id}, "
        f"metadata={identity.langfuse_metadata}"
    )
    
    return identity
