# -*- coding: utf-8 -*-
"""색인에서 '외곽 1개 + 내부 홀 몇 개' 형태의 판재 후보를 고른다."""
import json, numpy as np
import product          # 제품 고유값 모음 — 기본값 500pro
SCR = product.SCR
d = json.load(open(SCR + r'\index.json', encoding='utf-8'))
P = d['polys']; C = d['circles']; T = d['texts']
pb = np.array([[p[2], p[3], p[4], p[5]] for p in P], float)
w = pb[:,2]-pb[:,0]; h = pb[:,3]-pb[:,1]
area = w*h
cb = np.array([[c[2]-c[4], c[3]-c[4], c[2]+c[4], c[3]+c[4]] for c in C], float) if C else np.zeros((0,4))
tp = np.array([[t[2], t[3]] for t in T], float)

# 후보: 300mm~4000mm 급, 종횡비 과하지 않은 것
ok = np.where((w > 300) & (h > 200) & (w < 6000) & (h < 4000))[0]
order = ok[np.argsort(-area[ok])]
print('size-filtered candidates:', len(order))

res = []
for i in order[:400]:
    x0,y0,x1,y1 = pb[i]
    inp = np.where((pb[:,0] >= x0-1) & (pb[:,1] >= y0-1) & (pb[:,2] <= x1+1) & (pb[:,3] <= y1+1))[0]
    inp = inp[inp != i]
    inc = np.where((cb[:,0] >= x0) & (cb[:,1] >= y0) & (cb[:,2] <= x1) & (cb[:,3] <= y1))[0] if len(cb) else []
    nt = int(((tp[:,0] >= x0) & (tp[:,0] <= x1) & (tp[:,1] >= y0) & (tp[:,1] <= y1)).sum()) if len(tp) else 0
    nin = len(inp) + len(inc)
    if 1 <= nin <= 40:
        res.append((i, len(inp), len(inc), nt))

print('shape-filtered:', len(res))
for i, npo, nci, nt in res[:25]:
    x0,y0,x1,y1 = pb[i]
    # 근처 텍스트 (bbox + 400mm 여유)
    m = (tp[:,0] > x0-400) & (tp[:,0] < x1+400) & (tp[:,1] > y0-400) & (tp[:,1] < y1+400)
    near = [T[k][4] for k in np.where(m)[0]][:12]
    print('idx%-7d h=%-8s layer=%-14s %.0f x %.0f mm  poly_in=%d circ_in=%d txt_in=%d @(%.0f,%.0f)'
          % (i, P[i][0], P[i][1][:14], w[i], h[i], npo, nci, nt, x0, y0))
    print('    near:', ' | '.join(near))
