#!/usr/bin/env python3
from PIL import Image, ImageDraw
import sys


def draw_dashed_line(draw, start, end, fill, width=2, dash=10, gap=6):
    x1, y1 = start
    x2, y2 = end

    if x1 == x2:
        y = y1
        while y < y2:
            y_end = min(y + dash, y2)
            draw.line((x1, y, x2, y_end), fill=fill, width=width)
            y += dash + gap
    elif y1 == y2:
        x = x1
        while x < x2:
            x_end = min(x + dash, x2)
            draw.line((x, y1, x_end, y2), fill=fill, width=width)
            x += dash + gap


def make_grid(width, height, cell_size, output=None):
    if width % cell_size != 0 or height % cell_size != 0:
        raise ValueError('宽度和高度必须能被格子大小整除')

    cols = width // cell_size
    rows = height // cell_size

    img = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    draw = ImageDraw.Draw(img)

    line_color = (80, 80, 80, 255)
    line_width = 4
    dash = 14
    gap = 8
    edge = line_width // 2

    for c in range(cols + 1):
        x = c * cell_size
        if c == 0:
            x = edge
        elif c == cols:
            x = width - 1 - edge
        draw_dashed_line(draw, (x, edge), (x, height - 1 - edge), fill=line_color, width=line_width, dash=dash, gap=gap)

    for r in range(rows + 1):
        y = r * cell_size
        if r == 0:
            y = edge
        elif r == rows:
            y = height - 1 - edge
        draw_dashed_line(draw, (edge, y), (width - 1 - edge, y), fill=line_color, width=line_width, dash=dash, gap=gap)

    if output is None:
        output = f'grid_{width}x{height}_{cell_size}.png'

    img.save(output)
    print(f'已生成: {output}')
    print(f'尺寸: {width}x{height}')
    print(f'网格: {cols}x{rows}')
    print(f'单元格: {cell_size}x{cell_size}')


def main():
    if len(sys.argv) < 4:
        print('用法: python3 grid.py <width> <height> <cell_size> [output.png]')
        print('示例: python3 grid.py 4352 512 128')
        sys.exit(1)

    width = int(sys.argv[1])
    height = int(sys.argv[2])
    cell_size = int(sys.argv[3])
    output = sys.argv[4] if len(sys.argv) >= 5 else None

    make_grid(width, height, cell_size, output)


if __name__ == '__main__':
    main()
