"""
AI Event Tracking API — Track và display AI agent events trong chatbot.
"""

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from typing import Optional, List, Dict, Any
from datetime import datetime
import json
import logging

from common.event_bus import event_bus

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/ai-event", tags=["AI Event Tracking"])


class EventLog(BaseModel):
    """Model cho event log storage."""
    id: str
    timestamp: str
    event_type: str
    channel: str
    user_id: Optional[str] = None
    data: Dict[str, Any]
    metadata: Optional[Dict[str, Any]] = None


# In-memory store (production nên dùng Redis/DB)
_event_logs: List[EventLog] = []
_max_logs = 1000  # Giới hạn số logs trong memory


def _generate_id() -> str:
    """Generate unique ID cho event."""
    import uuid
    return str(uuid.uuid4())[:8]


@router.get("/logs")
async def get_event_logs(
    limit: int = 50,
    event_type: Optional[str] = None,
    user_id: Optional[str] = None
) -> List[EventLog]:
    """
    Lấy danh sách event logs.

    Args:
        limit: Số lượng logs trả về (default 50)
        event_type: Filter theo event type
        user_id: Filter theo user ID
    """
    logs = _event_logs.copy()

    if event_type:
        logs = [log for log in logs if log.event_type == event_type]
    if user_id:
        logs = [log for log in logs if log.user_id == user_id]

    return logs[-limit:][::-1]  # Return latest first


@router.post("/publish")
async def publish_event(request: Request) -> Dict[str, Any]:
    """
    Publish một event mới.

    Body:
    {
        "event_type": "chat:search_completed",
        "channel": "in_app",
        "user_id": "user123",
        "data": { ... },
        "metadata": { ... }
    }
    """
    try:
        body = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    event_type = body.get("event_type")
    channel = body.get("channel", "in_app")
    user_id = body.get("user_id")
    data = body.get("data", {})
    metadata = body.get("metadata", {})

    if not event_type:
        raise HTTPException(status_code=400, detail="event_type is required")

    # Create log entry
    log = EventLog(
        id=_generate_id(),
        timestamp=datetime.now().isoformat(),
        event_type=event_type,
        channel=channel,
        user_id=user_id,
        data=data,
        metadata=metadata
    )

    # Store in memory
    _event_logs.append(log)
    if len(_event_logs) > _max_logs:
        _event_logs.pop(0)

    # Also publish to event bus nếu cần
    try:
        await event_bus.publish(event_type, {
            "event_id": log.id,
            "timestamp": log.timestamp,
            "user_id": user_id,
            **data
        })
    except Exception as e:
        logger.warning(f"Failed to publish to event bus: {e}")

    logger.info(f"[EVENT] {event_type} | user={user_id} | data={data}")

    return {
        "status": "ok",
        "event_id": log.id,
        "timestamp": log.timestamp
    }


@router.get("/stats")
async def get_event_stats() -> Dict[str, Any]:
    """Get statistics về events."""
    total = len(_event_logs)

    # Count by type
    by_type: Dict[str, int] = {}
    for log in _event_logs:
        by_type[log.event_type] = by_type.get(log.event_type, 0) + 1

    # Count by channel
    by_channel: Dict[str, int] = {}
    for log in _event_logs:
        by_channel[log.channel] = by_channel.get(log.channel, 0) + 1

    # Recent activity (last hour)
    one_hour_ago = datetime.now().timestamp() - 3600
    recent = 0
    for log in _event_logs:
        try:
            ts = datetime.fromisoformat(log.timestamp).timestamp()
            if ts > one_hour_ago:
                recent += 1
        except:
            pass

    return {
        "total": total,
        "recent_1h": recent,
        "by_type": by_type,
        "by_channel": by_channel,
        "max_capacity": _max_logs
    }


@router.delete("/logs")
async def clear_event_logs() -> Dict[str, Any]:
    """Clear tất cả event logs."""
    global _event_logs
    count = len(_event_logs)
    _event_logs = []
    logger.info(f"Cleared {count} event logs")
    return {
        "status": "ok",
        "cleared": count
    }


@router.get("/types")
async def get_event_types() -> List[str]:
    """Lấy danh sách tất cả event types có sẵn."""
    from common.notification.events import EventType
    return EventType.ALL
