import os
import shutil
from typing import List
from fastapi import File, Form, HTTPException, UploadFile
from sqlalchemy.orm import Session
from app.api.competitor_intensity import schema
from app.models.main.competitor_intensity import CompetitorIntensityBase, TblCompetitorIntensity
from app.utils.schemas_utils import CustomResponse
from app.dependency.authantication import JWTPayloadSchema
from app.locale.messages import Messages

class CompetitorIntensityService:
    def __init__(self, db:Session, token:JWTPayloadSchema):
        self.db = db
        self.token = token
        
    async def create_competitor(self, request:schema.CompetitorIntensityCreate, upload_image:UploadFile = Form(None)):
        if not upload_image:
            return CustomResponse(status="0", message="Upload image is required")
        image_filename = upload_image.filename
        image_path = f"uploads/{image_filename}"
        with open(image_path, "wb") as buffer:
            shutil.copyfileobj(upload_image.file, buffer)
        create_data = request.model_dump()
        create_data["upload_image"] = image_path 
        new_brand = TblCompetitorIntensity(**create_data)
        self.db.add(new_brand)
        self.db.commit()
        return CustomResponse(
            status="1",
            message="Upload image and created successfully",
            data={"Upload image": image_path}
        )

    
        
    async def get_group_competitor(self, group_id:int):
        new_get_group_competitor = TblCompetitorIntensity.get_competitor(group_id, self.db)
        if not new_get_group_competitor:
            raise HTTPException(status_code=404, detail="Get group ID not found")
        return [schema.CompetitorIntensityResponse.model_validate(get_group) for get_group in new_get_group_competitor]
    
    async def update_competitor(self,competitor_id:int, request:schema.CompetitorIntensityUpdate, upload_image:UploadFile = Form(None)):
        competitor = self.db.query(TblCompetitorIntensity).filter(TblCompetitorIntensity.competitor_id == competitor_id).first()
        if not competitor:
            return CustomResponse(status="0", message="Update ID not found")
        if request.total_square_footage is not None:
            competitor.total_square_footage = request.total_square_footage
        if request.assumptions is not None:
            competitor.assumptions = request.assumptions
        if request.group_id is not None:
                competitor.group_id = request.group_id
        if upload_image:
            image_filename = upload_image.filename
            image_path = f"uploads/{image_filename}"
            with open(image_path, "wb") as buffer:
                shutil.copyfileobj(upload_image.file, buffer)
            if competitor.upload_image and os.path.exists(competitor.upload_image):
                os.remove(competitor.upload_image)
            # if os.path.exists(brand.brand_image):
            #     os.remove(brand.brand_image)
            competitor.upload_image = image_path
        self.db.commit()
        self.db.refresh(competitor)
        return CustomResponse(status="1", message="Competitor updated successfully", data={"image_url": competitor.upload_image})
    
    async def delete_competitor(self, competitor_id:int):
        deleted_competitor = TblCompetitorIntensity.delete_competitor(competitor_id, self.db)
        if not deleted_competitor:
            return CustomResponse(status="-1", message="Competitor ID Not Found")
        return CustomResponse(status="1", message="Competitor Deleted Successfully")

        
        
        