from fastapi import APIRouter, Depends, HTTPException, status, Response
from sqlalchemy.orm import Session
from typing import List
from uuid import UUID
import httpx
from ..database import get_db
from ..models.stream import Stream
from ..models.chat_message import ChatMessage
from ..models.user import User
from ..schemas.chat import ChatMessageCreate, ChatMessageResponse
from ..auth import get_current_admin_user

router = APIRouter(prefix="/api/streams/{stream_id}/chat", tags=["chat"])


@router.post("/upload", response_model=List[ChatMessageResponse], status_code=status.HTTP_201_CREATED)
async def upload_chat(
    stream_id: UUID,
    messages: List[ChatMessageCreate],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    # Check if stream exists
    stream = db.query(Stream).filter(Stream.id == stream_id).first()
    
    if not stream:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Stream not found"
        )
    
    # Create chat messages
    chat_messages = []
    for msg_data in messages:
        chat_msg = ChatMessage(
            stream_id=stream_id,
            username=msg_data.username,
            message=msg_data.message,
            timestamp_offset=msg_data.timestamp_offset,
            color=msg_data.color,
            badges=msg_data.badges
        )
        db.add(chat_msg)
        chat_messages.append(chat_msg)
    
    db.commit()
    
    # Refresh all messages
    for msg in chat_messages:
        db.refresh(msg)
    
    return chat_messages


@router.get("", response_model=List[ChatMessageResponse])
async def get_chat_messages(
    stream_id: UUID,
    db: Session = Depends(get_db)
):
    # Check if stream exists
    stream = db.query(Stream).filter(Stream.id == stream_id).first()
    
    if not stream:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Stream not found"
        )
    
    # Get chat messages ordered by timestamp
    messages = db.query(ChatMessage).filter(
        ChatMessage.stream_id == stream_id
    ).order_by(ChatMessage.timestamp_offset).all()
    
    return messages


@router.get("/proxy-image")
async def proxy_image(url: str):
    """Proxy images (badges, emotes, etc.) to avoid CORS issues"""
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.get(url)
            if response.status_code != 200:
                raise HTTPException(
                    status_code=response.status_code, 
                    detail=f"Failed to fetch image: {response.status_code}"
                )
            
            # Return the image with appropriate headers
            return Response(
                content=response.content,
                media_type=response.headers.get("content-type", "image/png"),
                headers={
                    "Cache-Control": "public, max-age=86400",  # Cache for 24 hours
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Methods": "GET",
                    "Access-Control-Allow-Headers": "*",
                }
            )
    except httpx.TimeoutException:
        raise HTTPException(status_code=504, detail="Image fetch timeout")
    except httpx.RequestError as e:
        raise HTTPException(status_code=502, detail=f"Failed to fetch image: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
