"""Canvas events router — batch write and query canvas event logs."""

from fastapi import APIRouter, Depends, HTTPException, Query
from typing import List, Optional
from datetime import datetime

from modules.auth.supabase_bearer import SupabaseBearer
from modules.transcription.models import CanvasEventCreate, CanvasEventResponse

router = APIRouter()


def get_supabase_client():
    """Get Supabase service role client."""
    from modules.database.supabase.utils.client import SupabaseServiceRoleClient
    return SupabaseServiceRoleClient()


def get_user_id(credentials=Depends(SupabaseBearer())) -> str:
    """Extract user_id from Supabase JWT token."""
    return credentials.get("sub", credentials.get("user_id", ""))


@router.post("/canvas-events")
async def batch_write_canvas_events(
    events: List[CanvasEventCreate],
    user_id: str = Depends(get_user_id),
):
    """Batch write canvas events."""
    supabase = get_supabase_client()
    
    # Filter events to only this user's
    user_events = [e for e in events if e.user_id == user_id]
    
    if not user_events:
        return {"message": "No events to write", "count": 0}
    
    event_data = [e.model_dump() for e in user_events]
    
    result = supabase.supabase.table("canvas_events").insert(event_data).execute()
    
    return {"message": f"Wrote {len(event_data)} events", "count": len(event_data)}


@router.get("/canvas-events", response_model=List[CanvasEventResponse])
async def get_canvas_events(
    session_id: Optional[str] = Query(None),
    user_id: str = Depends(get_user_id),
    limit: int = Query(100, ge=1, le=1000),
):
    """Get canvas events for a session or user."""
    supabase = get_supabase_client()
    
    query = supabase.supabase.table("canvas_events").select("*").eq("user_id", user_id)
    
    if session_id:
        query = query.eq("session_id", session_id)
    
    query = query.order("timestamp", desc=True).limit(limit)
    
    result = query.execute()
    
    return result.data
