
# from fastapi import (
#     APIRouter,
#     UploadFile,
#     File,
#     Response,
#     Header,
#     HTTPException,
#     Depends,
# )

# from fastapi.security import (
#     HTTPBearer,
#     HTTPAuthorizationCredentials,
# )

# from fastapi.concurrency import run_in_threadpool

# from app.utils.jwt import verify_access_token

# from app.modules.replaceBG.replaceBG_service import (
#     replace_background_service
# )

# from app.modules.device_limit.device_limit_repository import (
#     DeviceLimitRepository
# )

# from app.modules.user_subscription.user_subscription_service import (
#     UserSubscriptionService
# )

# router = APIRouter()

# security = HTTPBearer(auto_error=False)

# limit_repo = DeviceLimitRepository()

# subscription_service = UserSubscriptionService()


# @router.post("/replace-background")
# async def replace_background(

#     image: UploadFile = File(...),

#     background: UploadFile = File(...),

#     device_id: str = Header(
#         ...,
#         alias="X-Device-Id"
#     ),

#     credentials: HTTPAuthorizationCredentials = Depends(
#         security
#     )
# ):

#     premium_user = False



#     if credentials:

#         token = credentials.credentials

#         payload = verify_access_token(token)

#         if payload:

#             premium_user = await subscription_service.has_active_subscription(
#                 payload["_id"]
#             )


#     if not premium_user:

#         allowed = await limit_repo.check_and_increment_limit(
#             device_id
#         )

#         if not allowed:

#             raise HTTPException(
#                 status_code=403,
#                 detail={
#                     "success": False,
#                     "trigger_subscription": True,
#                     "message": "Daily limit reached"
#                 }
#             )

#     image_bytes = await image.read()

#     background_bytes = await background.read()

#     result = await run_in_threadpool(

#         replace_background_service,

#         image_bytes,

#         background_bytes

#     )

#     return Response(

#         content=result,

#         media_type="image/png"

#     )


from fastapi import (
    APIRouter,
    UploadFile,
    File,
    Response,
    Header,
    HTTPException,
    Depends,
)

from fastapi.security import (
    HTTPBearer,
    HTTPAuthorizationCredentials,
)

from fastapi.concurrency import run_in_threadpool

from app.utils.jwt import verify_access_token

from app.modules.replaceBG.replaceBG_service import (
    replace_background_service
)

from app.modules.device_limit.device_limit_repository import (
    DeviceLimitRepository
)

from app.modules.user_subscription.user_subscription_service import (
    UserSubscriptionService
)


router = APIRouter()

security = HTTPBearer(
    auto_error=False
)

limit_repo = DeviceLimitRepository()

subscription_service = UserSubscriptionService()


@router.post("/replace-background")
async def replace_background(

    image: UploadFile = File(...),

    background: UploadFile = File(...),

    device_id: str = Header(
        ...,
        alias="X-Device-Id"
    ),

    credentials: HTTPAuthorizationCredentials = Depends(
        security
    )

):

    # Premium User Check
    premium_user = False

    if credentials:

        token = credentials.credentials

        payload = verify_access_token(
            token
        )

        if payload:

            premium_user = (
                await subscription_service.has_active_subscription(
                    payload["_id"]
                )
            )


    # Free / Reward Limit Check
    usage_info = None

    if not premium_user:

        usage_info = (
            await limit_repo.check_and_increment_limit(
                device_id
            )
        )

      
        # No Free Image + No Reward
        if not usage_info["allowed"]:

            raise HTTPException(

                status_code=403,

                detail={

                    "success": False,

                    "show_reward_ad": True,

                    "message": (
                        "Daily free limit reached. "
                        "Watch ad to continue."
                    ),

                    "free_count": (
                        usage_info["free_count"]
                    ),

                    "reward": (
                        usage_info["reward"]
                    ),

                    "adCount": (
                        usage_info["adCount"]
                    ),

                    "remaining_free": (
                        usage_info["remaining_free"]
                    )

                }

            )

   
    # Read Images
    image_bytes = await image.read()

    background_bytes = await background.read()

    # Process Image
    result = await run_in_threadpool(

        replace_background_service,

        image_bytes,

        background_bytes

    )


    # Response Headers
    headers = {}

    if usage_info:

        headers["X-Free-Count"] = str(
            usage_info["free_count"]
        )

        headers["X-Reward"] = str(
            usage_info["reward"]
        )

        headers["X-Ad-Count"] = str(
            usage_info["adCount"]
        )

        headers["X-Remaining-Free"] = str(
            usage_info["remaining_free"]
        )

        headers["X-Usage-Type"] = (
            usage_info["source"]
        )

    else:

        # Premium user
        headers["X-Usage-Type"] = "premium"

    # Return Result
    return Response(

        content=result,

        media_type="image/png",

        headers=headers

    )