"""
리비전 비교 API 엔드포인트
"""

from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import Optional

from ..database import get_db
from ..auth.middleware import get_current_user
from ..services.revision_comparison_service import RevisionComparisonService
from ..auth.models import User
from ..utils.logger import get_logger

logger = get_logger(__name__)

router = APIRouter(prefix="/revision-comparison", tags=["Revision Comparison"])


@router.post("/compare")
async def compare_revisions(
    current_file_id: int = Query(..., description="현재 파일 ID"),
    previous_file_id: int = Query(..., description="이전 파일 ID"),
    category_filter: Optional[str] = Query(None, description="카테고리 필터"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    두 리비전 간 자재 비교
    """
    
    try:
        comparison_service = RevisionComparisonService(db)
        
        comparison_result = comparison_service.compare_revisions(
            current_file_id=current_file_id,
            previous_file_id=previous_file_id,
            category_filter=category_filter
        )
        
        logger.info(f"Revision comparison completed: {current_file_id} vs {previous_file_id}")
        
        return {
            "success": True,
            "data": comparison_result,
            "message": "리비전 비교 완료"
        }
        
    except Exception as e:
        logger.error(f"Failed to compare revisions: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"리비전 비교 중 오류가 발생했습니다: {str(e)}"
        )


@router.get("/category/{current_file_id}/{previous_file_id}/{category}")
async def get_category_comparison(
    current_file_id: int,
    previous_file_id: int,
    category: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    특정 카테고리의 리비전 비교
    """
    
    if category == 'PIPE':
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="PIPE 카테고리는 별도 처리가 필요합니다."
        )
    
    try:
        comparison_service = RevisionComparisonService(db)
        
        comparison_result = comparison_service.get_category_comparison(
            current_file_id=current_file_id,
            previous_file_id=previous_file_id,
            category=category
        )
        
        logger.info(f"Category comparison completed: {category} ({current_file_id} vs {previous_file_id})")
        
        return {
            "success": True,
            "data": comparison_result,
            "message": f"{category} 카테고리 비교 완료"
        }
        
    except Exception as e:
        logger.error(f"Failed to compare category {category}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"카테고리 비교 중 오류가 발생했습니다: {str(e)}"
        )
