from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import func, case
from src.utils.db import get_db
from src.apps.auth.controller import get_current_user
from src.apps.stores.models import Branch
from src.apps.recommendations.models import Recommendation

# FastAPI Router
router = APIRouter()

@router.get("/recommendations_list")
def get_stored_recommendations(
    branch_id: int, 
    page: int = Query(1, description="Page number (starts from 1)", ge=1),
    page_size: int = Query(10, description="Number of records per page", ge=1, le=100),
    db: Session = Depends(get_db), 
    user=Depends(get_current_user)  
):
    """
    API to fetch recommendations from the database for a specific branch.
    Sorted by severity: High → Medium → Low, then by rank.
    Includes pagination.
    """
    # Verify user access
    branch = db.query(Branch).filter(
        Branch.branch_id == branch_id,
        Branch.user_id == user.user_id
    ).first()

    if not branch:
        raise HTTPException(
            status_code=403,
            detail={"status": False, "code": 403, "message": "Unauthorized access to this branch", "data": {}}
        )

    try:
        # Fetch total recommendations count
        total_recommendations = db.query(func.count(Recommendation.recommendation_id)).filter(
            Recommendation.branch_id == branch_id
        ).scalar()

        # Fetch paginated recommendations
        recommendations = db.query(Recommendation).filter(
            Recommendation.branch_id == branch_id
        ).order_by(
            case(
                (Recommendation.severity.ilike("high"), 1),
                (Recommendation.severity.ilike("medium"), 2),
                (Recommendation.severity.ilike("low"), 3),
                else_=99
            ),
            Recommendation.rank
        ).limit(page_size).offset((page - 1) * page_size).all()

        # If no recommendations found
        if not recommendations:
            return {
                "status": False,
                "code": 404,
                "message": "No recommendations found for this branch.",
                "data": []
            }

        # Convert to JSON format
        response_data = [
            {
                "recommendation": rec.recommendation,
                "topic": rec.topic,
                "severity": rec.severity,
                "rank": rec.rank,
                "branch_id": rec.branch_id
            }
            for rec in recommendations
        ]

        # Calculate total pages
        total_pages = (total_recommendations + page_size - 1) // page_size

        return {
            "status": True,
            "code": 200,
            "message": "Recommendations fetched successfully",
            "data": response_data,
            "pagination": {
                "total_records": total_recommendations,
                "total_pages": total_pages,
                "current_page": page,
                "page_size": page_size
            }
        }

    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={"status": False, "code": 500, "message": "Error fetching recommendations", "error": str(e)}
        )
