#!/usr/bin/env python3
"""產生 A4 直式信封標籤 PDF — 字大、清晰"""
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import os

for fp in [
    '/System/Library/Fonts/PingFang.ttc',
    '/System/Library/Fonts/STHeiti Light.ttc',
]:
    if os.path.exists(fp):
        try:
            pdfmetrics.registerFont(TTFont('CJK', fp, subfontIndex=0))
            break
        except:
            pass

OUT = os.path.expanduser('~/Desktop/信封標籤.pdf')
pw, ph = A4

c = canvas.Canvas(OUT, pagesize=A4)

lw = 90 * mm
lh = 42 * mm
gx = 5 * mm
gy = 4 * mm
mx = (pw - 2 * lw - gx) / 2
my = 10 * mm

sender = [
    ("五洲國際通運有限公司", True, 16),
    ("桃園市大園區航翔路113號3樓", False, 13),
    ("（Q3001B室）", False, 13),
    ("分機 #695　關務 吳小姐", False, 12),
]

receiver = [
    ("鄰哥實業有限公司", True, 16),
    ("桃園市中壢區文化二路326號", False, 13),
    ("電話：0983-879-138", False, 12),
]

usable_h = ph - 2 * my
rows = int((usable_h + gy) / (lh + gy))

def draw_label(x, y, lines):
    c.setStrokeColorRGB(0.15, 0.15, 0.15)
    c.setLineWidth(1.5)
    c.roundRect(x, y, lw, lh, 3 * mm)
    
    tx = x + 5 * mm
    ty = y + lh - 9 * mm
    
    for text, bold, size in lines:
        if bold:
            c.setFont('CJK', size)
            c.setFillColorRGB(0, 0, 0)
        else:
            c.setFont('CJK', size)
            c.setFillColorRGB(0.1, 0.1, 0.1)
        c.drawString(tx, ty, text)
        ty -= 7 * mm

for row in range(rows):
    ly = ph - my - (row + 1) * lh - row * gy
    draw_label(mx, ly, sender)
    draw_label(mx + lw + gx, ly, receiver)

c.save()
print(f'✅ PDF 產出：{OUT}')
print(f'   直式 A4，共 {rows} 列 × 2 = {rows * 2} 份標籤')
