# -*- coding: utf-8 -*-
"""Pass 7b: 도번별 '단품도' 콜아웃 근방을 작은 셀로 잘라 몽타주 PNG 로 묶는다.
   한 장에 9개 도번씩 → 그림으로 직접 보고 도번-두께를 짝지어 읽는다."""
import json, os, math
import numpy as np
import matplotlib; matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pass7_tiles import load, locate, PN

SCR = os.path.dirname(os.path.abspath(__file__))
W, H = 620.0, 460.0   # 셀 하나가 담는 도면 범위(mm)
COLS, ROWS = 3, 3


def draw_cell(ax, cx, cy, d1, d2, T, label):
    X0, X1 = cx - W * 0.35, cx + W * 0.65
    Y0, Y1 = cy - H * 0.62, cy + H * 0.38

    def inw(x, y):
        return X0 <= x <= X1 and Y0 <= y <= Y1
    for l in d2['lines']:
        if inw(l[0], l[1]) or inw(l[2], l[3]):
            ax.plot([l[0], l[2]], [l[1], l[3]], '-', color='0.55', lw=0.5)
    for a in d2['arcs']:
        if inw(a[0], a[1]):
            s, e = a[3], a[4]
            if e < s: e += 360
            t = np.radians(np.linspace(s, e, 30))
            ax.plot(a[0] + a[2] * np.cos(t), a[1] + a[2] * np.sin(t), '-', color='0.55', lw=0.5)
    for c in d1['circles']:
        if inw(c[2], c[3]):
            ax.add_patch(plt.Circle((c[2], c[3]), c[4], fill=False, color='0.65', lw=0.5))
    for x, y, s in T:
        if inw(x, y) and s:
            tgt = bool(PN.search(s.replace(' ', '')))
            ax.text(x, y, s[:42], fontsize=7.2,
                    color=('#b00020' if tgt else '#083b1e'),
                    weight=('bold' if tgt else 'normal'), va='bottom', clip_on=True)
    ax.plot([cx], [cy], marker='v', color='#0033cc', ms=7)
    ax.set_xlim(X0, X1); ax.set_ylim(Y0, Y1)
    ax.set_aspect('equal'); ax.set_xticks([]); ax.set_yticks([])
    ax.set_title(label, fontsize=9, color='#0033cc')


if __name__ == '__main__':
    d1, d2, T = load()
    wanted = json.load(open(SCR + r'\vlm_targets.json', encoding='utf-8'))
    pts = locate(T, wanted)
    cells = [(p, pts[p][0]) for p in wanted if pts.get(p)]
    print('셀', len(cells))
    os.makedirs(SCR + r'\mont', exist_ok=True)
    per = COLS * ROWS
    idx = []
    for i in range(0, len(cells), per):
        chunk = cells[i:i + per]
        fig, axes = plt.subplots(ROWS, COLS, figsize=(13.5, 10.0))
        for ax in np.ravel(axes):
            ax.axis('off')
        for j, (p, (x, y)) in enumerate(chunk):
            ax = np.ravel(axes)[j]; ax.axis('on')
            draw_cell(ax, x, y, d1, d2, T, p)
        out = SCR + r'\mont\m%02d.png' % (i // per)
        plt.tight_layout(); plt.savefig(out, dpi=118); plt.close(fig)
        idx.append({'png': out, 'pns': [c[0] for c in chunk]})
        print(os.path.basename(out), [c[0][-8:] for c in chunk])
    json.dump(idx, open(SCR + r'\mont\index.json', 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
