from __future__ import annotations

import argparse
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont


def load_font(size: int, *, bold: bool = False):
    candidates: list[str] = []
    if bold:
        candidates.extend([r"C:\Windows\Fonts\msyhbd.ttc", r"C:\Windows\Fonts\simhei.ttf"])
    candidates.extend([r"C:\Windows\Fonts\msyh.ttc", r"C:\Windows\Fonts\simsun.ttc", r"C:\Windows\Fonts\arial.ttf"])
    for path in candidates:
        try:
            return ImageFont.truetype(path, size=size)
        except OSError:
            continue
    return ImageFont.load_default()


def resize_to_width(img: Image.Image, width: int) -> Image.Image:
    if img.width == width:
        return img
    h = int(img.height * width / img.width)
    return img.resize((width, h), Image.Resampling.LANCZOS)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Compose UV/LFL report image from 3 source images.")
    parser.add_argument("--table-image", required=True)
    parser.add_argument("--line-image", required=True)
    parser.add_argument("--entry-image", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--content-width", type=int, default=1040)
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    table_img = resize_to_width(Image.open(args.table_image).convert("RGB"), args.content_width)
    line_img = resize_to_width(Image.open(args.line_image).convert("RGB"), args.content_width)
    entry_img = resize_to_width(Image.open(args.entry_image).convert("RGB"), args.content_width)

    pad_x = 34
    top_h = 56
    gap = 12
    bottom_pad = 24

    canvas_w = args.content_width + pad_x * 2
    canvas_h = top_h + table_img.height + gap + line_img.height + gap + entry_img.height + bottom_pad
    canvas = Image.new("RGB", (canvas_w, canvas_h), "#e7e7e7")
    draw = ImageDraw.Draw(canvas)

    title_font = load_font(36, bold=True)
    brand_font = load_font(24, bold=True)
    draw.text((pad_x, 14), "UV LFL", fill="#111111", font=title_font)
    draw.text((canvas_w - 210, 18), "CHARLES & KEITH", fill="#c9c9c9", font=brand_font)

    y = top_h
    canvas.paste(table_img, (pad_x, y))
    y += table_img.height + gap
    canvas.paste(line_img, (pad_x, y))
    y += line_img.height + gap
    canvas.paste(entry_img, (pad_x, y))

    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    canvas.save(output_path)
    print(str(output_path))


if __name__ == "__main__":
    main()
