# -*- coding: utf-8 -*-
"""각 뷰에서 항번 풍선 지시선 끝점 주변의 부재 윤곽(직사각형)을 실측해
   그 부재가 그 뷰에서 '면으로 보이는지(외곽 치수)' '옆으로 보이는지(두께)'를 판정한다.
   두께 PL 값이 판정 기준 — 도면에 그려진 두 선 간격이 PL 과 같으면 그 뷰에서 옆모습이다."""
import json, math, sys
import numpy as np

SCR = r'C:\Users\user\AppData\Local\Temp\claude\E-----Claude--20260728-claude-code-2-1-219\8defc145-8ae5-48d0-9058-355f3d9ae8ed\scratchpad'

VIEWS = {
    'LEFT':  (327200, 3950, 328250, 5700),   # 좌측면도  (drawing x -> Y, y -> Z)
    'FRONT': (328400, 3950, 329400, 5700),   # 정면도    (x -> X, y -> Z)
    'RIGHT': (329800, 3950, 330750, 5700),   # 우측면도  (x -> -Y, y -> Z)
    'SECC':  (330880, 3950, 331830, 5700),   # SECTION C-C 평면 (x -> X?, y -> Y)
    'SECA':  (327200, 6000, 328600, 7100),
    'MIDT':  (328600, 6000, 330000, 7100),
    'SECB':  (330000, 6000, 331100, 7100),
}


def load_lines():
    d2 = json.load(open(SCR + r'\index2.json', encoding='utf-8'))
    return np.array([l[:4] for l in d2['lines']], dtype=float)


def view_of(x, y):
    for k, (a, b, c, d) in VIEWS.items():
        if a < x < c and b < y < d:
            return k
    return None


def seg_in(L, box):
    a, b, c, d = box
    m = (((L[:, 0] > a) & (L[:, 0] < c) & (L[:, 1] > b) & (L[:, 1] < d)) |
         ((L[:, 2] > a) & (L[:, 2] < c) & (L[:, 3] > b) & (L[:, 3] < d)))
    return L[m]


def main():
    L = load_lines()
    balls = json.load(open(SCR + r'\asm31_balloons.json'))
    for b in balls:
        if not b['tip']:
            continue
        b['view'] = view_of(*b['tip']) or view_of(b['cx'], b['cy'])
    # 뷰별 전체 윤곽 범위
    print('=== 뷰별 도형 범위 ===')
    for k, box in VIEWS.items():
        S = seg_in(L, box)
        if not len(S):
            print(k, 'none'); continue
        xs = np.concatenate([S[:, 0], S[:, 2]]); ys = np.concatenate([S[:, 1], S[:, 3]])
        print('%-6s n=%3d  x %.1f..%.1f (w %.1f)   y %.1f..%.1f (h %.1f)'
              % (k, len(S), xs.min(), xs.max(), xs.max() - xs.min(),
                 ys.min(), ys.max(), ys.max() - ys.min()))
    print('=== 풍선 -> 뷰 ===')
    for b in sorted(balls, key=lambda z: (z['item'] or 99)):
        print(b['item'], b.get('view'), b['tip'])
    json.dump(balls, open(SCR + r'\asm31_balloons.json', 'w'), indent=1)


if __name__ == '__main__':
    main()
