"""第8章 検算：四色問題の論文の著者の Web サイトにある図（トンボの羽）から地図を復元する

図：https://web.sfc.keio.ac.jp/~takefuji/image/flyfly.gif（筆者は 2026-11-26 に取得。図は各自でダウンロードして、このファイルと同じフォルダに置く）
羽は赤・黄・緑・青の4色で塗り分けられている。隣どうしは必ず違う色なので、
「同じ色で縦横斜めにつながった画素のかたまり」を1つの地域とみなし（図の縮小で斜めにだけつながった地域を割らないため）、
5画素以下のかたまりは縮小でできた色の点とみなして除く（MIN_PIXELS）。
違う色の画素が縦横に接している地域の組を「隣」とみなす（斜めだけの接触は隣としない）。
体（明るい青 67,114,255）と黒（目・脚）と白（背景）は地図に入れない。

出力：dragonfly_adjacency.csv（地域番号の組）、地域数・隣接の組数・各地域の画素数の分布
"""
import os
import sys
from collections import deque

import numpy as np
from PIL import Image

MIN_PIXELS = 6
WING = {(255, 0, 0): 0, (255, 255, 0): 1, (0, 255, 0): 2, (0, 0, 255): 3}


def build(path):
    rgb = np.array(Image.open(path).convert("RGB"))
    h, w, _ = rgb.shape
    color = np.full((h, w), -1, dtype=np.int64)
    for c, k in WING.items():
        color[(rgb == c).all(axis=2)] = k
    lab = np.full((h, w), -1, dtype=np.int64)
    n = 0
    for y in range(h):
        for x in range(w):
            if color[y, x] < 0 or lab[y, x] >= 0:
                continue
            q = deque([(y, x)])
            lab[y, x] = n
            while q:
                cy, cx = q.popleft()
                for ny, nx in ((cy + 1, cx), (cy - 1, cx), (cy, cx + 1), (cy, cx - 1),
                               (cy + 1, cx + 1), (cy + 1, cx - 1), (cy - 1, cx + 1), (cy - 1, cx - 1)):
                    if 0 <= ny < h and 0 <= nx < w and lab[ny, nx] < 0 and color[ny, nx] == color[y, x]:
                        lab[ny, nx] = n
                        q.append((ny, nx))
            n += 1
    sizes = np.bincount(lab[lab >= 0], minlength=n)
    keep = np.where(sizes >= MIN_PIXELS)[0]
    remap = np.full(n, -1, dtype=np.int64)
    remap[keep] = np.arange(len(keep))
    lab = np.where(lab >= 0, remap[np.maximum(lab, 0)], -1)
    n = len(keep)
    edges = set()
    for a, b in ((lab[:-1, :], lab[1:, :]), (lab[:, :-1], lab[:, 1:])):
        m = (a >= 0) & (b >= 0) & (a != b)
        for u, v in zip(a[m], b[m]):
            edges.add((min(u, v), max(u, v)))
    region_color = np.array([color[lab == i][0] for i in range(n)])
    sizes = sizes[keep]
    return n, edges, region_color, sizes


def main():
    path = sys.argv[1]
    n, edges, rc, sizes = build(path)
    same = sum(1 for u, v in edges if rc[u] == rc[v])
    print(f"地域 {n}、隣接 {len(edges)} 組、同じ色どうしの隣接 {same} 組（0 なら図は正しい塗り分け）")
    print(f"色ごとの地域数: 赤 {(rc == 0).sum()} 黄 {(rc == 1).sum()} 緑 {(rc == 2).sum()} 青 {(rc == 3).sum()}")
    print(f"地域の画素数: 最小 {sizes.min()}、中央値 {int(np.median(sizes))}、最大 {sizes.max()}、"
          f"（{MIN_PIXELS}画素未満は除いた）")
    deg = np.zeros(n, dtype=int)
    for u, v in edges:
        deg[u] += 1
        deg[v] += 1
    print(f"隣の数: 平均 {deg.mean():.2f}、最大 {deg.max()}、隣のない地域 {(deg == 0).sum()}")
    out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dragonfly_adjacency.csv")
    with open(out, "w", encoding="utf-8") as f:
        f.write("a,b\n")
        for u, v in sorted(edges):
            f.write(f"{u},{v}\n")
    print("書き出し:", out)


if __name__ == "__main__":
    main()
