# -*- coding: utf-8 -*-
"""2110DN-0031 조립도(1/2 시트) 항번 풍선 + 지시선 화살표 끝점 추출.
풍선(원 r=18.8) 안의 숫자 = 항번, 원에 붙은 지시선을 따라가 끝점(= 그 부재를 가리키는 위치)을 구한다."""
import json, math, collections, sys

SCR = r'C:\Users\user\AppData\Local\Temp\claude\E-----Claude--20260728-claude-code-2-1-219\8defc145-8ae5-48d0-9058-355f3d9ae8ed\scratchpad'
X0, Y0, X1, Y1 = 326830, 3900, 331790, 8130
RB = 18.8


def load():
    d1 = json.load(open(SCR + r'\index.json', encoding='utf-8'))
    d2 = json.load(open(SCR + r'\index2.json', encoding='utf-8'))
    return d1, d2


def inw(x, y):
    return X0 < x < X1 and Y0 < y < Y1


def main():
    d1, d2 = load()
    balls = [c for c in d1['circles'] if inw(c[2], c[3]) and abs(c[4] - RB) < 1.0]
    texts = [t for t in d1['texts'] if inw(t[2], t[3])]
    lines = [l for l in d2['lines'] if inw(l[0], l[1]) or inw(l[2], l[3])]

    # 풍선 안 숫자
    out = []
    for b in balls:
        cx, cy = b[2], b[3]
        cand = [t for t in texts if math.hypot(t[2] - cx, t[3] - cy) < RB * 1.6
                and t[4].strip().isdigit()]
        item = int(cand[0][4].strip()) if cand else None
        out.append({'item': item, 'cx': cx, 'cy': cy})

    # 지시선: 원 둘레에서 시작하는 선분 → 연결 체인 따라 자유단
    def near(p, q, tol=1.5):
        return math.hypot(p[0] - q[0], p[1] - q[1]) < tol

    segs = [((l[0], l[1]), (l[2], l[3])) for l in lines]
    for b in out:
        cx, cy = b['cx'], b['cy']
        start = None
        for s in segs:
            for i in (0, 1):
                p = s[i]
                if abs(math.hypot(p[0] - cx, p[1] - cy) - RB) < 2.0:
                    start = (s, i)
                    break
            if start:
                break
        if not start:
            b['tip'] = None
            b['chain'] = 0
            continue
        s, i = start
        cur = s[1 - i]
        prev = s[i]
        used = {segs.index(s)}
        n = 1
        for _ in range(6):
            nxt = None
            for j, t in enumerate(segs):
                if j in used:
                    continue
                for k in (0, 1):
                    if near(t[k], cur) and not near(t[1 - k], prev):
                        nxt = (j, t[1 - k])
                        break
                if nxt:
                    break
            if not nxt:
                break
            used.add(nxt[0])
            prev, cur = cur, nxt[1]
            n += 1
        b['tip'] = [round(cur[0], 2), round(cur[1], 2)]
        b['chain'] = n

    out.sort(key=lambda b: (b['item'] if b['item'] else 99, b['cx']))
    json.dump(out, open(SCR + r'\asm31_balloons.json', 'w'), indent=1)
    for b in out:
        print(b['item'], round(b['cx']), round(b['cy']), b['tip'], 'seg%d' % b['chain'])


if __name__ == '__main__':
    main()
