from typing import Optional
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks
from pydantic import BaseModel, Field
import logging
import time # For timing logs
from src.services.rag_service import get_service_instance
from src.core.config import settings

logger = logging.getLogger("RERA_API")
# Professional Greetings Fast-Path
GREETINGS_MAP = {
    "hi": {
        "english": "Hi! I am FINRERA Agent. How can I help you today?",
        "hindi": "नमस्ते! मैं FINRERA एजेंट हूँ। आज मैं आपकी क्या मदद कर सकता हूँ?",
        "gujarati": "નમસ્તે! હું FINRERA એજન્ટ છું. આજે હું તમને શું મદદ કરી શકું?"
    },
    "hello": {
        "english": "Hello! I am your FINRERA AI Assistant. What RERA information can I assist you with?",
        "hindi": "नमस्ते! मैं आपका FINRERA AI असिस्टेंट हूँ। मैं RERA की कौन सी जानकारी में आपकी सहायता कर सकता हूँ?",
        "gujarati": "નમસ્તે! હું તમારો FINRERA AI આસિસ્ટન્ટ છું. RERA ની કઈ માહિતીમાં હું તમને મદદ કરી શકું?"
    }
}

def detect_basic_greeting(msg: str):
    clean = msg.lower().strip().replace("?", "").replace("!", "").replace(".", "")
    # Check for simple greetings
    if clean in ["hi", "hello", "hey", "hola", "namaste"]:
        return "hi"
    # Check for "how are you" variants
    if clean in ["how are you", "how r u", "how are you doing"]:
        return "how_are_you"
    return None

GREETINGS_MAP["how_are_you"] = {
    "english": "I am doing great! I am your FINRERA AI Assistant. How can I help you today?",
    "hindi": "मैं ठीक हूँ! मैं आपका FINRERA AI असिस्टेंट हूँ। आज मैं आपकी क्या मदद कर सकता हूँ?",
    "gujarati": "હું મજામાં છું! હું તમારો FINRERA AI આસિસ્ટન્ટ છું. આજે હું તમને શું મદદ કરી શકું?"
}

router = APIRouter(prefix="/ai", tags=["Legal Services"])

# Helper for background history saving
async def save_chat_history(user_identifier, user_msg, ai_response, full_name, phone_number, source="website"):
    from src.services.history_service import history_service
    try:
        await history_service.add_message(user_identifier, role="user", message=user_msg, full_name=full_name, phone_number=phone_number, source=source)
        await history_service.add_message(user_identifier, role="model", message=ai_response, full_name=full_name, phone_number=phone_number, source=source)
    except Exception as e:
        logger.error(f"Background history save failed: {e}")

_assistant_service = None

def get_assistant_service():
    global _assistant_service
    if _assistant_service is None:
        _assistant_service = get_service_instance()
    return _assistant_service

class LegalQueryRequest(BaseModel):
    user_message: str = Field(..., min_length=1)
    user_id: Optional[str] = None
    phone_number: Optional[str] = None  # Backward compatibility
    contact_id: Optional[str] = None  # Backward compatibility
    full_name: Optional[str] = None  # Backward compatibility

class LegalQueryResponse(BaseModel):
    message: str
    status: str = "True"

@router.post("/chat", response_model=LegalQueryResponse)
async def chat_assessment(request: LegalQueryRequest, background_tasks: BackgroundTasks):
    try:
        from src.services.history_service import history_service
        
        # Determine source and identifier
        if request.phone_number:
            # WhatsApp flow
            source = "whatsapp"
            identifier = request.phone_number
        else:
            # Website flow
            source = "website"
            identifier = request.user_id or "guest_user"
        
        # --- FAST PATH: Simple Greetings ---
        greeting_key = detect_basic_greeting(request.user_message)
        if greeting_key:
            # Simple word-based language detection for greetings
            msg_lower = request.user_message.lower()
            lang = "english"
            if any(word in msg_lower for word in ["કેમ", "નમસ્તે", "છો"]): lang = "gujarati"
            elif any(word in msg_lower for word in ["नमस्ते", "कैसे", "हो"]): lang = "hindi"
            
            msg = GREETINGS_MAP[greeting_key][lang]
            
            background_tasks.add_task(save_chat_history, identifier, request.user_message, msg, request.full_name, request.phone_number, source)
            return LegalQueryResponse(message=msg)
        
        # 1. Fetch Last 10 Messages for Context
        past_msgs = await history_service.get_recent_history(identifier, limit=10, source=source)
        
        # 2. Format history for AI (Gemini format)
        formatted_history = "No prior history."
        if past_msgs:
            formatted_history = "\n".join([f"{m['role'].upper()}: {m['parts']}" for m in past_msgs])

        # 3. Get AI Assessment
        service = get_assistant_service()
        response = await service.get_legal_assessment(request.user_message, chat_history=formatted_history)

        # 4. Save to History as Background Task (Saves time for the user)
        background_tasks.add_task(
            save_chat_history, 
            identifier, 
            request.user_message, 
            response, 
            request.full_name, 
            request.phone_number,
            source
        )

        return LegalQueryResponse(message=response)
    except Exception as error:
        logger.error(f"API Error: {error}")
        raise HTTPException(status_code=500, detail=str(error))

@router.get("/health")
async def health():
    return {"status": "healthy"}

@router.get("/test-chat")
async def test_chat(message: str = "What is RERA?"):
    """Browser-friendly GET endpoint for testing"""
    try:
        service = get_assistant_service()
        response = await service.get_legal_assessment(message)
        return {"message": response, "status": "True"}
    except Exception as e:
        return {"error": str(e), "status": "False"}

@router.get("/history/{identifier}")
async def get_user_history(identifier: str, source: str = "website"):
    """
    Fetch complete chat history for a user (for frontend display).
    Query params:
    - source: 'whatsapp' or 'website' (default: website)
    For WhatsApp: identifier is contact_id
    For Website: identifier is user_id
    """
    try:
        from src.services.history_service import history_service
        history_data = await history_service.get_full_history(identifier, source=source)
        return history_data
    except Exception as e:
        logger.error(f"History fetch error: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/all-user-chats")
async def get_all_user_chats(page: int = 1, limit: int = 20):
    """
    Get all user chat histories with user details from admins collection.
    Uses MongoDB $lookup to join collections.
    Supports pagination.
    
    Query params:
    - page: Page number (default: 1)
    - limit: Items per page (default: 20)
    """
    try:
        from src.services.history_service import history_service
        result = await history_service.get_all_chats_with_user_details(page=page, limit=limit)
        return result
    except Exception as e:
        logger.error(f"All chats fetch error: {e}")
        raise HTTPException(status_code=500, detail=str(e))
