from fastapi import HTTPException
from sqlalchemy.orm import Session
import app.api.catchment_potential.schemas as schemas
from app.dependency.authantication import JWTPayloadSchema
from app.locale.messages import Messages
from app.models.main.catchment_potential import CatchmentPotentialBase,TblCatchmentPotential
from app.utils.common_utils import calculate_potential_number_of_household_consumption, fill_and_calculate_potential_households
from app.utils.schemas_utils import CustomResponse

class Catchment_Potential:
    def __init__(self, db: Session, token: JWTPayloadSchema):
        self.db = db
        self.token = token

    async def create_catchment_potential(self, request: schemas.catchmentPotentialCreat):
        created_user = CatchmentPotentialBase.model_validate(request.model_dump())
        created_user.potential_number_of_households = calculate_potential_number_of_household_consumption(created_user)
        TblCatchmentPotential.create(created_user, self.db)
        self.db.commit()
        return CustomResponse(status="1", message=Messages.CATCHMENT_POTENTIAL_CREAT)

    async def get_total_consumption_by_group(self, group_id: int) -> schemas.TotalPotentialResponse:
        locations = (self.db.query(TblCatchmentPotential).filter(TblCatchmentPotential.group_id == group_id).all())
        if not locations:
            raise HTTPException(status_code=404,detail=Messages.CATCHMENT_NOT_FOUND)
        total_consumption = sum(loc.number_of_households * loc.percentage_of_segment for loc in locations)
        return schemas.TotalPotentialResponse(group_id=group_id,potential_number_of_households=int(total_consumption))

    async def get_catchment(self, catch_id: int):
        catchment = TblCatchmentPotential.get_by_id(catch_id, self.db)
        if not catchment:
            raise HTTPException(status_code=404,detail=Messages.CATCHMENT_NOT_FOUND)
        return schemas.GetPotentialResponse.model_validate(catchment)

    async def update_catchment(self, request: schemas.UpdatePotential):
        if request.catch_id is None:
            raise HTTPException(status_code=404, detail=Messages.CATCHMENT_ID_REQUIRED)
        existing = TblCatchmentPotential.get_by_id(request.catch_id, self.db)
        if not existing:
            raise HTTPException(status_code=404, detail=Messages.CATCHMENT_NOT_FOUND)
        update_data = request.model_dump(exclude_unset=True)
        updated_data = fill_and_calculate_potential_households(update_data, existing)
        validated_model = CatchmentPotentialBase(**updated_data)
        assert validated_model.catch_id is not None
        TblCatchmentPotential.update(validated_model.catch_id, validated_model, self.db)
        return CustomResponse(status="1", message=Messages.CATCHMENT_UPDATE)
    
    async def get_catchment_poteneial_by_group(self, group_id: int):
        Catchment_Potential = (self.db.query(TblCatchmentPotential).filter(TblCatchmentPotential.group_id == group_id).all())
        return [schemas.catchmentPotentialResponse.model_validate(loc) for loc in Catchment_Potential]

    async def delete_catchment(self, catch_id: int):
        deleted = TblCatchmentPotential.delete(catch_id, self.db)
        if not deleted:
            raise HTTPException(status_code=404,detail=Messages.CATCHMENT_NOT_FOUND)
        return CustomResponse(status="1", message=Messages.CATCHMENT_DELETED)
