
from fastapi import HTTPException
from sqlalchemy import desc, select
from sqlalchemy.orm import Session
from app.api.pre_selected_category import schema
from app.api.store_formate import schemas
from app.dependency.authantication import JWTPayloadSchema
from app.locale.messages import Messages
from app.models.main.group import TblGroup
from app.models.main.main_data import TblMainData
from app.models.main.pre_selected_caregory import PreSelectedCategoryBase, TblPreSelectedCategory
from app.models.main.store_formate import TblStoreFormat
from app.utils.schemas_utils import CustomResponse 

class PreSelectedCategoryService:
    def __init__(self, db: Session,token:JWTPayloadSchema):
        self.db = db
        self.token = token
        
    async def post(self, request:schemas.StoreFormateCreate11):
        group = self.db.query(TblGroup).filter(TblGroup.group_id == request.group_id).first()
        if not group:
            return CustomResponse(status="0", message="Group not found")
        
        result = self.db.execute(
            select(TblMainData)
            .where(
                (TblMainData.format_type == group.category_assigned) |
                (TblMainData.format_type == group.category)
            )
            .order_by(desc(TblMainData.data_id))
            .limit(1)
        ) 
        
        main_data = result.scalar_one_or_none()
        
        if not main_data:
            return CustomResponse(status="0", message="Main data not found for the group's category")
            
        merchandise_map = {
            'Low': main_data.no_of_cats_l or 0,
            'Medium': main_data.no_of_cats_m or 0,
            'High': main_data.no_of_cats_h or 0
        }
        
        merchandise_text = request.merchandise
        if merchandise_text not in merchandise_map:
            return CustomResponse(status="0", message="Invalid merchandise value (Low, Medium, High required)")
        merchandise_value = merchandise_map[merchandise_text]
        
        new_store = schemas.StoreFormateRes.model_validate(request)
        new_store.merchandise=str(merchandise_value)
        new_store_db = TblStoreFormat(**new_store.model_dump())
        self.db.add(new_store_db)
        self.db.commit()
        self.db.refresh(new_store_db)
        return CustomResponse(status="1", message=Messages.PRE_CREATE)
        
        
    # async def post(self):
    #     request = self.db.execute(
    #         select(TblMainData)
    #         .where(
    #             (TblMainData.format_type == TblGroup.category_assigned) |
    #             (TblMainData.format_type == TblGroup.category)
    #         )
    #         .order_by(desc(TblMainData.data_id))
    #         .limit(1)
    #     )
        
    #     main_data = request.scalar_one_or_none()
        
    #     if not main_data:
    #         return CustomResponse(status="0", message="Main data not found for the group's category")
        
    #     merchandise_map = {
    #         'Low' : main_data.no_of_cats_l or 0,
    #         'Medium' : main_data.no_of_cats_m or 0,
    #         'High' : main_data.no_of_cats_h or 0
    #     }
        
    #     merchandise_text = TblStoreFormat.merchandise
    #     if merchandise_text not in merchandise_map:
    #         return CustomResponse(status="0", message="Invalid merchandise value (Low, Medium, High required)")
    #     merchandise_value = merchandise_map[merchandise_text]
        
    #     new_store = TblStoreFormat.merchandise = str(merchandise_value)
    #     # new_store_db = TblStoreFormat(**new_store.model)
    #     self.db.add(new_store)
    #     self.db.commit()
    #     self.db.refresh(new_store)
    #     return CustomResponse(status="1", message=Messages.PRE_CREATE)
    
    # class PreSelectedCategoryService:
    # def __init__(self, db: Session, token: JWTPayloadSchema):
    #     self.db = db
    #     self.token = token

    # async def post(self):
    # # 1. Get latest main data for the group
    #     request = self.db.execute(
    #         select(TblMainData)
    #         .where(
    #             (TblMainData.format_type == TblGroup.category_assigned) |
    #             (TblMainData.format_type == TblGroup.category)
    #         )
    #         .order_by(desc(TblMainData.data_id))
    #         .limit(1)
    #     )
    #     main_data = request.scalar_one_or_none()

    #     if not main_data:
    #         return CustomResponse(
    #             status="0",
    #             message="Main data not found for the group's category"
    #         )

    #     # 2. Map levels to category numbers
    #     merchandise_map = {
    #         "Low": main_data.no_of_cats_l or 0,
    #         "Medium": main_data.no_of_cats_m or 0,
    #         "High": main_data.no_of_cats_h or 0,
    #     }

    #     # 3. Fetch the actual merchandise level from TblGroup (previous module)
    #     group = self.db.query(TblStoreFormat).filter(TblStoreFormat.group_id == self.token.group_id).first()
    #     if not group:
    #         return CustomResponse(status="0", message="Merchandise level not found for group")

    #     merchandise_text = group.merchandise  # "Low" | "Medium" | "High"

    #     if merchandise_text not in merchandise_map:
    #         return CustomResponse(
    #             status="0",
    #             message="Invalid merchandise value (must be Low, Medium, High)"
    #         )

    #     merchandise_value = merchandise_map[merchandise_text]

    #     # 4. Save/update in TblStoreFormat
    #     new_store = TblStoreFormat(
    #         merchandise=merchandise_text,
    #         no_of_categories=str(merchandise_value)
    #     )
    #     self.db.add(new_store)
    #     self.db.commit()
    #     self.db.refresh(new_store)

    #     # 5. Build response message
    #     return CustomResponse(
    #         status="1",
    #         message="Pre-selected category levels retrieved successfully",
    #         data={
    #             "Level of Category or Merchandise": merchandise_text,
    #             "Number of Categories Available": merchandise_value
    #         }
    #     )


    # async def create_pre_selected_category(self, request:schema.PreSelectedCategoryCreate):
    #     created_pre_selected_category = PreSelectedCategoryBase.model_validate(request.model_dump())
    #     TblPreSelectedCategory.create_pre_selected_category(created_pre_selected_category, self.db)
    #     self.db.commit()
    #     return CustomResponse(status="1", message=Messages.PRE_CREATE)
        
    async def get(self,group_id:int) -> list[schema.PreValidation]: 
        
        get_data = self.db.query(TblStoreFormat.merchandise).filter(TblStoreFormat.group_id == group_id).all()
        if not get_data:
            raise HTTPException(status_code=404, detail="not found")
        return [schema.PreValidation.model_validate(get_datas) for get_datas in get_data]
    
    # async def get_category(self, data_id:int) -> list[schema.GetCategory]:
    #     get_data = self.db.query(TblStoreFormat,TblMainData).filter(TblStoreFormat.merchandise == TblMainData.no_of_cats_l or TblStoreFormat.merchandise == TblMainData.no_of_cats_m or TblStoreFormat.merchandise == TblMainData.no_of_cats_h).all()
    #     if not get_data:
    #         raise HTTPException(status_code=404, detail="not found")
    #     return [schema.GetCategory.model_validate(get_datas) for get_datas in get_data]
    
    # async def upload_retails(file: UploadFile, db: Session, student_id: int):
    #     if student_id is None:
    #         raise HTTPException(status_code=400, detail="student_id missing in token.")
        
    #     student = db.query(TblStudent).filter(TblStudent.student_id == student_id).first()
    #     if not student:
    #         raise HTTPException(status_code=404, detail="Student not found.")

    #     if not student.group:
    #         raise HTTPException(status_code=404, detail="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)
            
    #     pd.read_excel(file_location)
    #     group.excel_pre_select = file_location
    #     db.commit()

    #     return {
    #         "message": "File uploaded and group updated successfully!",
    #         "group_id": group.group_id,
    #         "filename": file_location
    #     }