import json
import logging
from typing import List, Optional

from datetime import datetime, date

from fastapi import APIRouter, Body, Depends, HTTPException, Query
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession

from core.database import get_db
from services.ticket_summaries import Ticket_summariesService

# Set up logging
logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/v1/entities/ticket_summaries", tags=["ticket_summaries"])


# ---------- Pydantic Schemas ----------
class Ticket_summariesData(BaseModel):
    """Entity data schema (for create/update)"""
    ticket_id: str
    last_reply_id: str
    summary: str
    model: str = None


class Ticket_summariesUpdateData(BaseModel):
    """Update entity data (partial updates allowed)"""
    ticket_id: Optional[str] = None
    last_reply_id: Optional[str] = None
    summary: Optional[str] = None
    model: Optional[str] = None


class Ticket_summariesResponse(BaseModel):
    """Entity response schema"""
    id: int
    ticket_id: str
    last_reply_id: str
    summary: str
    model: Optional[str] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    class Config:
        from_attributes = True


class Ticket_summariesListResponse(BaseModel):
    """List response schema"""
    items: List[Ticket_summariesResponse]
    total: int
    skip: int
    limit: int


class Ticket_summariesBatchCreateRequest(BaseModel):
    """Batch create request"""
    items: List[Ticket_summariesData]


class Ticket_summariesBatchUpdateItem(BaseModel):
    """Batch update item"""
    id: int
    updates: Ticket_summariesUpdateData


class Ticket_summariesBatchUpdateRequest(BaseModel):
    """Batch update request"""
    items: List[Ticket_summariesBatchUpdateItem]


class Ticket_summariesBatchDeleteRequest(BaseModel):
    """Batch delete request"""
    ids: List[int]


# ---------- Routes ----------
@router.get("", response_model=Ticket_summariesListResponse)
async def query_ticket_summariess(
    query: str = Query(None, description="Query conditions (JSON string)"),
    sort: str = Query(None, description="Sort field (prefix with '-' for descending)"),
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(20, ge=1, le=2000, description="Max number of records to return"),
    fields: str = Query(None, description="Comma-separated list of fields to return"),
    db: AsyncSession = Depends(get_db),
):
    """Query ticket_summariess with filtering, sorting, and pagination"""
    logger.debug(f"Querying ticket_summariess: query={query}, sort={sort}, skip={skip}, limit={limit}, fields={fields}")
    
    service = Ticket_summariesService(db)
    try:
        # Parse query JSON if provided
        query_dict = None
        if query:
            try:
                query_dict = json.loads(query)
            except json.JSONDecodeError:
                raise HTTPException(status_code=400, detail="Invalid query JSON format")
        
        result = await service.get_list(
            skip=skip, 
            limit=limit,
            query_dict=query_dict,
            sort=sort,
        )
        logger.debug(f"Found {result['total']} ticket_summariess")
        return result
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error querying ticket_summariess: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


@router.get("/all", response_model=Ticket_summariesListResponse)
async def query_ticket_summariess_all(
    query: str = Query(None, description="Query conditions (JSON string)"),
    sort: str = Query(None, description="Sort field (prefix with '-' for descending)"),
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(20, ge=1, le=2000, description="Max number of records to return"),
    fields: str = Query(None, description="Comma-separated list of fields to return"),
    db: AsyncSession = Depends(get_db),
):
    # Query ticket_summariess with filtering, sorting, and pagination without user limitation
    logger.debug(f"Querying ticket_summariess: query={query}, sort={sort}, skip={skip}, limit={limit}, fields={fields}")

    service = Ticket_summariesService(db)
    try:
        # Parse query JSON if provided
        query_dict = None
        if query:
            try:
                query_dict = json.loads(query)
            except json.JSONDecodeError:
                raise HTTPException(status_code=400, detail="Invalid query JSON format")

        result = await service.get_list(
            skip=skip,
            limit=limit,
            query_dict=query_dict,
            sort=sort
        )
        logger.debug(f"Found {result['total']} ticket_summariess")
        return result
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error querying ticket_summariess: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


@router.get("/{id}", response_model=Ticket_summariesResponse)
async def get_ticket_summaries(
    id: int,
    fields: str = Query(None, description="Comma-separated list of fields to return"),
    db: AsyncSession = Depends(get_db),
):
    """Get a single ticket_summaries by ID"""
    logger.debug(f"Fetching ticket_summaries with id: {id}, fields={fields}")
    
    service = Ticket_summariesService(db)
    try:
        result = await service.get_by_id(id)
        if not result:
            logger.warning(f"Ticket_summaries with id {id} not found")
            raise HTTPException(status_code=404, detail="Ticket_summaries not found")
        
        return result
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error fetching ticket_summaries {id}: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


@router.post("", response_model=Ticket_summariesResponse, status_code=201)
async def create_ticket_summaries(
    data: Ticket_summariesData,
    db: AsyncSession = Depends(get_db),
):
    """Create a new ticket_summaries"""
    logger.debug(f"Creating new ticket_summaries with data: {data}")
    
    service = Ticket_summariesService(db)
    try:
        result = await service.create(data.model_dump())
        if not result:
            raise HTTPException(status_code=400, detail="Failed to create ticket_summaries")
        
        logger.info(f"Ticket_summaries created successfully with id: {result.id}")
        return result
    except ValueError as e:
        logger.error(f"Validation error creating ticket_summaries: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Error creating ticket_summaries: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


@router.post("/batch", response_model=List[Ticket_summariesResponse], status_code=201)
async def create_ticket_summariess_batch(
    request: Ticket_summariesBatchCreateRequest,
    db: AsyncSession = Depends(get_db),
):
    """Create multiple ticket_summariess in a single request"""
    logger.debug(f"Batch creating {len(request.items)} ticket_summariess")
    
    service = Ticket_summariesService(db)
    results = []
    
    try:
        for item_data in request.items:
            result = await service.create(item_data.model_dump())
            if result:
                results.append(result)
        
        logger.info(f"Batch created {len(results)} ticket_summariess successfully")
        return results
    except Exception as e:
        await db.rollback()
        logger.error(f"Error in batch create: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Batch create failed: {str(e)}")


@router.put("/batch", response_model=List[Ticket_summariesResponse])
async def update_ticket_summariess_batch(
    request: Ticket_summariesBatchUpdateRequest,
    db: AsyncSession = Depends(get_db),
):
    """Update multiple ticket_summariess in a single request"""
    logger.debug(f"Batch updating {len(request.items)} ticket_summariess")
    
    service = Ticket_summariesService(db)
    results = []
    
    try:
        for item in request.items:
            # Only include non-None values for partial updates
            update_dict = {k: v for k, v in item.updates.model_dump().items() if v is not None}
            result = await service.update(item.id, update_dict)
            if result:
                results.append(result)
        
        logger.info(f"Batch updated {len(results)} ticket_summariess successfully")
        return results
    except Exception as e:
        await db.rollback()
        logger.error(f"Error in batch update: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Batch update failed: {str(e)}")


@router.put("/{id}", response_model=Ticket_summariesResponse)
async def update_ticket_summaries(
    id: int,
    data: Ticket_summariesUpdateData,
    db: AsyncSession = Depends(get_db),
):
    """Update an existing ticket_summaries"""
    logger.debug(f"Updating ticket_summaries {id} with data: {data}")

    service = Ticket_summariesService(db)
    try:
        # Only include non-None values for partial updates
        update_dict = {k: v for k, v in data.model_dump().items() if v is not None}
        result = await service.update(id, update_dict)
        if not result:
            logger.warning(f"Ticket_summaries with id {id} not found for update")
            raise HTTPException(status_code=404, detail="Ticket_summaries not found")
        
        logger.info(f"Ticket_summaries {id} updated successfully")
        return result
    except HTTPException:
        raise
    except ValueError as e:
        logger.error(f"Validation error updating ticket_summaries {id}: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Error updating ticket_summaries {id}: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


@router.delete("/batch")
async def delete_ticket_summariess_batch(
    request: Ticket_summariesBatchDeleteRequest,
    db: AsyncSession = Depends(get_db),
):
    """Delete multiple ticket_summariess by their IDs"""
    logger.debug(f"Batch deleting {len(request.ids)} ticket_summariess")
    
    service = Ticket_summariesService(db)
    deleted_count = 0
    
    try:
        for item_id in request.ids:
            success = await service.delete(item_id)
            if success:
                deleted_count += 1
        
        logger.info(f"Batch deleted {deleted_count} ticket_summariess successfully")
        return {"message": f"Successfully deleted {deleted_count} ticket_summariess", "deleted_count": deleted_count}
    except Exception as e:
        await db.rollback()
        logger.error(f"Error in batch delete: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Batch delete failed: {str(e)}")


@router.delete("/{id}")
async def delete_ticket_summaries(
    id: int,
    db: AsyncSession = Depends(get_db),
):
    """Delete a single ticket_summaries by ID"""
    logger.debug(f"Deleting ticket_summaries with id: {id}")
    
    service = Ticket_summariesService(db)
    try:
        success = await service.delete(id)
        if not success:
            logger.warning(f"Ticket_summaries with id {id} not found for deletion")
            raise HTTPException(status_code=404, detail="Ticket_summaries not found")
        
        logger.info(f"Ticket_summaries {id} deleted successfully")
        return {"message": "Ticket_summaries deleted successfully", "id": id}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error deleting ticket_summaries {id}: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")