#!/usr/bin/env python3
# (C) 2023 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED.  OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.


"""Code snippet for add logo."""

import os
import sys
import warnings
from pathlib import Path

from PIL import Image


def main() -> int:
    """Adding logo to image."""
    argv = sys.argv

    if len(sys.argv) != 4:  # noqa: PLR2004
        warnings.warn(
            f"Usage {argv[0]} <in_image> <logo_image> <out_image>", stacklevel=1
        )
        return 1

    in_image, logo, out_image = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])
    add_logo(in_image, logo, out_image)
    return os.EX_OK


def add_logo(input_filename: Path, logo_filename: Path, output_filename: Path) -> bool:
    """Add the togo to the bottom left corner of the image."""
    in_image = Image.open(input_filename)
    logo_image = Image.open(logo_filename)

    # resize logo
    w_size = int(min(in_image.size[0], in_image.size[1]) * 0.30)
    w_percent = w_size / float(logo_image.size[0])
    h_size = int(float(logo_image.size[1]) * float(w_percent))

    new_image = logo_image.resize((w_size, h_size))
    mbox: tuple[int, int, int, int] | None = in_image.getbbox()
    new_box: tuple[int, int, int, int] | None = new_image.getbbox()
    if not mbox or not new_box:
        warnings.warn(
            "Cannot calculate bounding box of input or output image", stacklevel=2
        )
        return False

    # right bottom corner
    box = (mbox[2] - new_box[2], mbox[3] - new_box[3])
    in_image.paste(new_image, box)
    in_image.save(output_filename)

    return True


if __name__ == "__main__":
    sys.exit(main())
