
# # from rembg import remove
# # from fastapi import UploadFile, HTTPException
# # from PIL import Image, ImageColor
# # import io

# # from app.utils.file_validator import validate_image
# # from app.services.history_service import save_image_history


# # async def remove_image_background(
# #     file: UploadFile,
# #     user: dict,
# #     bg_color: str = None,
# #     background_file: UploadFile = None
# # ):
# #     await validate_image(file)

# #     input_data = await file.read()

# #     try:
# #         # STEP 1: Remove background (AI)
# #         output_data = remove(input_data)

# #         # Convert to RGBA (important for transparency)
# #         foreground = Image.open(
# #             io.BytesIO(output_data)
# #         ).convert("RGBA")

# #         # =========================
# #         # CASE 1: Custom background image
# #         # =========================
# #         if background_file:
# #             await validate_image(background_file)

# #             bg_data = await background_file.read()

# #             background = Image.open(
# #                 io.BytesIO(bg_data)
# #             ).convert("RGBA")

# #             # Resize background to match foreground
# #             background = background.resize(foreground.size)

# #             final_image = Image.alpha_composite(
# #                 background,
# #                 foreground
# #             )

# #         # =========================
# #         # CASE 2: Background color
# #         # =========================
# #         elif bg_color:
# #             try:
# #                 rgb_color = ImageColor.getcolor(bg_color, "RGBA")
# #             except Exception:
# #                 raise HTTPException(
# #                     status_code=400,
# #                     detail="Invalid background color"
# #                 )

# #             background = Image.new(
# #                 "RGBA",
# #                 foreground.size,
# #                 rgb_color
# #             )

# #             final_image = Image.alpha_composite(
# #                 background,
# #                 foreground
# #             )

# #         # =========================
# #         # CASE 3: No background (transparent)
# #         # =========================
# #         else:
# #             return output_data

# #         # Convert final image to bytes
# #         buffer = io.BytesIO()
# #         final_image.save(buffer, format="PNG")
# #         buffer.seek(0)

# #         return buffer.getvalue()

# #     except Exception as e:
# #         raise HTTPException(
# #             status_code=500,
# #             detail=f"Processing failed: {str(e)}"
# #         )


# from rembg import remove
# from fastapi import UploadFile, HTTPException
# from PIL import Image, ImageColor
# import io

# from app.utils.file_validator import validate_image
# from app.services.history_service import save_image_history


# async def remove_image_background(
#     file: UploadFile,
#     user: dict,
#     bg_color: str = None,
#     background_file: UploadFile = None
# ):
#     await validate_image(file)

#     input_data = await file.read()

#     try:
#         # =========================
#         # STEP 1: Remove background
#         # =========================
#         output_data = remove(input_data)

#         # Convert AI result to image
#         foreground = Image.open(
#             io.BytesIO(output_data)
#         ).convert("RGBA")

#         # =========================
#         # STEP 2: Detect background type
#         # =========================
#         bg_type = "none"

#         # =========================
#         # CASE 1: Custom image background
#         # =========================
#         if background_file:
#             bg_type = "image"

#             await validate_image(background_file)

#             bg_data = await background_file.read()

#             background = Image.open(
#                 io.BytesIO(bg_data)
#             ).convert("RGBA")

#             # Resize background
#             background = background.resize(foreground.size)

#             final_image = Image.alpha_composite(
#                 background,
#                 foreground
#             )

#         # =========================
#         # CASE 2: Color background
#         # =========================
#         elif bg_color:
#             bg_type = "color"

#             try:
#                 rgb_color = ImageColor.getcolor(
#                     bg_color,
#                     "RGBA"
#                 )

#             except Exception:
#                 raise HTTPException(
#                     status_code=400,
#                     detail="Invalid background color"
#                 )

#             background = Image.new(
#                 "RGBA",
#                 foreground.size,
#                 rgb_color
#             )

#             final_image = Image.alpha_composite(
#                 background,
#                 foreground
#             )

#         # =========================
#         # CASE 3: Transparent background
#         # =========================
#         else:
#             final_image = foreground

#         # =========================
#         # STEP 3: Convert final image to bytes
#         # =========================
#         buffer = io.BytesIO()

#         final_image.save(buffer, format="PNG")

#         buffer.seek(0)

#         final_output = buffer.getvalue()

#         # =========================
#         # STEP 4: Save history
#         # =========================
#         await save_image_history(
#             user_phone=user["phone"],
#             filename=file.filename,
#             bg_type=bg_type
#         )

#         # =========================
#         # STEP 5: Return image
#         # =========================
#         return final_output
    
#     except HTTPException: 
#         raise
  
#     except Exception: 
#         raise HTTPException(
#             status_code=500,
#             detail="Internal server error"
#         )



# from rembg import remove

# from fastapi import (
#     UploadFile,
#     HTTPException
# )

# from PIL import (
#     Image,
#     ImageColor
# )

# import io

# from app.utils.file_validator import (
#     validate_image
# )

# from app.services.history_service import (
#     save_image_history
# )


# async def remove_image_background(
#     file: UploadFile,
#     user: dict,
#     bg_color: str = None,
#     background_file: UploadFile = None
# ):

#     await validate_image(file)

#     input_data = await file.read()

#     try:

#         output_data = remove(input_data)

#         foreground = Image.open(
#             io.BytesIO(output_data)
#         ).convert("RGBA")

#         bg_type = "none"

#         if background_file:

#             bg_type = "image"

#             await validate_image(
#                 background_file
#             )

#             bg_data = await background_file.read()

#             background = Image.open(
#                 io.BytesIO(bg_data)
#             ).convert("RGBA")

#             background = background.resize(
#                 foreground.size
#             )

#             final_image = Image.alpha_composite(
#                 background,
#                 foreground
#             )

#         elif bg_color:

#             bg_type = "color"

#             try:

#                 rgb_color = ImageColor.getcolor(
#                     bg_color,
#                     "RGBA"
#                 )

#             except Exception:

#                 raise HTTPException(
#                     status_code=400,
#                     detail="Invalid background color"
#                 )

#             background = Image.new(
#                 "RGBA",
#                 foreground.size,
#                 rgb_color
#             )

#             final_image = Image.alpha_composite(
#                 background,
#                 foreground
#             )

#         else:

#             final_image = foreground

#         buffer = io.BytesIO()

#         final_image.save(
#             buffer,
#             format="PNG",
#             optimize=True
#         )

#         buffer.seek(0)

#         final_output = buffer.getvalue()

#         await save_image_history(
#             user_phone=user["phone"],
#             filename=file.filename,
#             bg_type=bg_type
#         )

#         return final_output

#     except HTTPException:
#         raise

#     except Exception:

#         raise HTTPException(
#             status_code=500,
#             detail="Internal server error"
#         )


# new code without auth 

from rembg import remove

from fastapi import (
    UploadFile,
    HTTPException
)

from PIL import (
    Image,
    ImageColor
)

import io

from app.utils.file_validator import (
    validate_image
)

from app.services.history_service import (
    save_image_history
)


async def remove_image_background(
    file: UploadFile,
    bg_color: str = None,
    background_file: UploadFile = None
):

    await validate_image(file)

    input_data = await file.read()

    try:

        output_data = remove(input_data)

        foreground = Image.open(
            io.BytesIO(output_data)
        ).convert("RGBA")

        bg_type = "none"

        if background_file:

            bg_type = "image"

            await validate_image(
                background_file
            )

            bg_data = await background_file.read()

            background = Image.open(
                io.BytesIO(bg_data)
            ).convert("RGBA")

            background = background.resize(
                foreground.size
            )

            final_image = Image.alpha_composite(
                background,
                foreground
            )

        elif bg_color:

            bg_type = "color"

            try:

                rgb_color = ImageColor.getcolor(
                    bg_color,
                    "RGBA"
                )

            except Exception:

                raise HTTPException(
                    status_code=400,
                    detail="Invalid background color"
                )

            background = Image.new(
                "RGBA",
                foreground.size,
                rgb_color
            )

            final_image = Image.alpha_composite(
                background,
                foreground
            )

        else:

            final_image = foreground

        buffer = io.BytesIO()

        final_image.save(
            buffer,
            format="PNG",
            optimize=True
        )

        buffer.seek(0)

        final_output = buffer.getvalue()

        await save_image_history(
            user_phone="guest",
            filename=file.filename,
            bg_type=bg_type
        )

        return final_output

    except HTTPException:
        raise

    except Exception:

        raise HTTPException(
            status_code=500,
            detail="Internal server error"
        )