import os
import shutil
import pandas as pd
from fastapi import APIRouter, Depends, UploadFile,File
from fastapi.responses import FileResponse, JSONResponse
from sqlalchemy.orm import Session
from app.api.pre_selected_category import service
from app.database.main.mysql import get_db
from app.dependency.authantication import JWTPayloadSchema, get_current_student
from app.models.main.student import TblStudent

pre_select_category_router = APIRouter()

@pre_select_category_router.post("/post", response_model_exclude_none=True)
async def post(db:Session = Depends(get_db),token: JWTPayloadSchema = Depends(get_current_student)):
    return await service.PreSelectedCategoryService(db,token).post()


@pre_select_category_router.get("download_excel")
async def download_excel_pree():
    file_path = "files/3Sample_Category_Sheet1_.xlsx"
    return FileResponse(
        path=file_path,
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        filename="3Sample_Category_Sheet1_.xlsx"
    )
    
UPLOAD_DIR = "uploaded_files"
os.makedirs(UPLOAD_DIR, exist_ok=True)

@pre_select_category_router.post("/upload_retails")
async def upload_retails(
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    token: JWTPayloadSchema = Depends(get_current_student)
):
    student_id = getattr(token, "student_id", None)
    if student_id is None:
        return JSONResponse(status_code=400, content={"error": "student_id missing in token."})
    
    student = db.query(TblStudent).filter(TblStudent.student_id == student_id).first()
    if not student:
        return JSONResponse(status_code=404, content={"error": "Student not found."})
    
    if not student.group:
        return JSONResponse(status_code=404, content={"error": "Group not assigned to this student."})
    
    group = student.group
    
    filename = file.filename or "uploaded_file.xlsx"
    file_location = os.path.join(UPLOAD_DIR, filename)
    with open(file_location, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
        
    df = pd.read_excel(file_location)
    
    group.excel_pre_select = file_location
    db.commit()
    
    return JSONResponse(content={
        "message": "File uploaded and group updated successfully!",
        "group_id": group.group_id,
        "filename": file_location
    })



# @pre_select_category_router.get("/Pre_get_merchandise", response_model_exclude_none=True)
# async def pre_get_merchendise(group_id:int, db:Session = Depends(get_db),token: JWTPayloadSchema = Depends(get_current_student)):
#     return await service.PreSelectedCategoryService(db, token).get_merchandise(group_id)

@pre_select_category_router.get("/Pre_get", response_model_exclude_none=True)
async def pre_get(group_id:int, db:Session = Depends(get_db),token: JWTPayloadSchema = Depends(get_current_student)):
    return await service.PreSelectedCategoryService(db, token).get_pre_select_category(group_id)

