"""Draw a 32x32 archery-bow sprite. Requires Pillow: pip install Pillow."""

from pathlib import Path

from PIL import Image, ImageDraw


OUT = Path(__file__).resolve().parent
PALETTE = {
    "outline": "#352635",
    "wood_shadow": "#754035",
    "wood": "#BA713D",
    "wood_light": "#E6A85A",
    "gold_shadow": "#A46838",
    "gold": "#F2CA72",
    "leather": "#5D3B3D",
    "wrap": "#AD6851",
    "string_shadow": "#716978",
    "string": "#F7E9CD",
}

sprite = Image.new("RGBA", (32, 32), (0, 0, 0, 0))
draw = ImageDraw.Draw(sprite)


def line(points, color, width=1):
    draw.line(points, fill=PALETTE[color], width=width)


# One-pixel flax string with a dark edge for visibility on light backgrounds.
line([(4, 5), (27, 28)], "string_shadow")
line([(4, 4), (27, 27)], "string")

# Recurved wooden limbs, drawn directly at native resolution.
limb = [
    (4, 4), (7, 5), (10, 4), (14, 5), (18, 7),
    (21, 9), (23, 11), (25, 14), (27, 18),
    (28, 22), (27, 25), (28, 28),
]
line(limb, "outline", 5)
line(limb, "wood_shadow", 3)
line([
    (4, 3), (7, 4), (10, 3), (14, 4), (18, 6),
    (21, 8), (23, 10), (26, 14), (28, 18),
    (29, 22), (28, 25), (29, 28),
], "wood_light")
line(limb, "wood")

# Leather grip with gold collars and diagonal bindings.
draw.polygon([(19, 8), (21, 6), (26, 11), (23, 14), (19, 10)],
             fill=PALETTE["outline"])
draw.polygon([(20, 8), (21, 7), (25, 11), (23, 13), (20, 10)],
             fill=PALETTE["leather"])
line([(20, 9), (22, 7)], "gold_shadow")
line([(19, 8), (21, 6)], "gold")
line([(23, 13), (25, 11)], "gold_shadow")
line([(24, 13), (26, 11)], "gold")
line([(21, 10), (23, 8)], "wrap")
line([(22, 11), (24, 9)], "wrap")
line([(23, 12), (25, 10)], "wrap")

# Reinforced nocks at the limb tips.
line([(3, 3), (5, 5)], "outline", 3)
line([(3, 3), (5, 5)], "gold")
line([(27, 26), (29, 28)], "outline", 3)
line([(27, 26), (29, 28)], "gold")
draw.point((4, 4), fill=PALETTE["string"])
draw.point((28, 27), fill=PALETTE["string"])

png_path = OUT / "archery_bow_32x32.png"
sprite.save(png_path)
sprite.resize((512, 512), Image.Resampling.NEAREST).save(
    OUT / "archery_bow_preview.png"
)

# An inspection view makes the transparent areas easy to see.
checker = Image.new("RGBA", (32, 32))
checker_draw = ImageDraw.Draw(checker)
for y in range(0, 32, 4):
    for x in range(0, 32, 4):
        color = "#26313F" if (x // 4 + y // 4) % 2 else "#303D4D"
        checker_draw.rectangle((x, y, x + 3, y + 3), fill=color)
checker.alpha_composite(sprite)
checker.resize((512, 512), Image.Resampling.NEAREST).save(
    OUT / "archery_bow_inspection.png"
)

with Image.open(png_path) as exported:
    assert exported.size == (32, 32)
    assert exported.mode == "RGBA"
    assert set(exported.getchannel("A").getdata()) == {0, 255}
print(f"Created {png_path} ({png_path.stat().st_size} bytes; 32x32 RGBA)")
