"""
Messages Controller for Mid Platform.
[AC-IDMP-08] Message report endpoint: POST /mid/messages/report
"""

import logging
import time
from typing import Annotated, Any

from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_session
from app.core.tenant import get_tenant_id
from app.models.mid.schemas import MessageReportRequest
from app.services.memory import MemoryService

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/mid", tags=["Mid Platform Messages"])


@router.post(
    "/messages/report",
    operation_id="reportMessages",
    summary="Report session messages and events",
    description="""
    [AC-IDMP-08] Report messages from channel to mid platform.
    
    Accepts messages from bot, human, or channel sources for session closure.
    Returns 202 Accepted for async processing.
    """,
    responses={
        202: {"description": "Accepted for async processing"},
        400: {"description": "Invalid request"},
    },
)
async def report_messages(
    request: Request,
    report_request: MessageReportRequest,
    session: Annotated[AsyncSession, Depends(get_session)],
) -> JSONResponse:
    """
    [AC-IDMP-08] Report messages from channel.
    
    Accepts and stores messages for session data completeness.
    Messages are stored asynchronously without blocking response.
    """
    tenant_id = get_tenant_id()
    
    if not tenant_id:
        from app.core.exceptions import MissingTenantIdException
        raise MissingTenantIdException()
    
    logger.info(
        f"[AC-IDMP-08] Message report: tenant={tenant_id}, "
        f"session={report_request.session_id}, count={len(report_request.messages)}"
    )
    
    try:
        memory_service = MemoryService(session)
        
        await memory_service.get_or_create_session(
            tenant_id=tenant_id,
            session_id=report_request.session_id,
        )
        
        messages_to_save = []
        for msg in report_request.messages:
            role = msg.role
            if msg.source == "human":
                role = "human"
            elif msg.source == "bot":
                role = "assistant"
            
            messages_to_save.append({
                "role": role,
                "content": msg.content,
            })
        
        if messages_to_save:
            await memory_service.append_messages(
                tenant_id=tenant_id,
                session_id=report_request.session_id,
                messages=messages_to_save,
            )
        
        logger.info(
            f"[AC-IDMP-08] Messages saved: tenant={tenant_id}, "
            f"session={report_request.session_id}, count={len(messages_to_save)}"
        )
        
        return JSONResponse(
            status_code=202,
            content={"status": "accepted", "session_id": report_request.session_id},
        )
    
    except Exception as e:
        logger.error(f"[AC-IDMP-08] Message report failed: {e}")
        return JSONResponse(
            status_code=202,
            content={"status": "accepted", "warning": str(e)},
        )
