#!/usr/bin/env python
import json
import sys
import os
sys.path.insert(0, 'c:/private/MCP-for-MS-Copilot')
from src.tools import _get_autocad_application, _get_insertion_point, _normalize_text, _cluster_by_y
layer_name = os.getenv("LAYER_SHOP_FIELD", "MATLIST")
categories_str = os.getenv("MATERIAL_CATEGORIES", "SHOP MATERIAL,FIELD MATERIAL")
categories = [cat.strip() for cat in categories_str.split(",") if cat.strip()]
row_tolerance = float(os.getenv("ROW_TOLERANCE", "3.0"))
acad, err = _get_autocad_application()
if err:
print(f"에러: {err}")
sys.exit(1)
doc = acad.ActiveDocument
text_items = []
for obj in doc.ModelSpace:
if obj.EntityName not in ["AcDbText", "AcDbMText"]:
continue
if obj.Layer != layer_name:
continue
point = _get_insertion_point(obj)
if not point:
continue
raw_text = getattr(obj, "TextString", "")
norm_text = _normalize_text(str(raw_text))
if not norm_text:
continue
text_items.append({
"text": str(raw_text),
"norm": norm_text,
"x": point[0],
"y": point[1],
})
category_map = {c.upper(): c for c in categories}
category_items = [item for item in text_items if item["norm"].upper() in category_map]
print("=" * 80)
print("카테고리 헤더 찾음:")
print("=" * 80)
for cat_item in category_items:
print(f" {cat_item['norm']} @ Y={cat_item['y']:.2f}")
for cat_item in sorted(category_items, key=lambda x: x["y"], reverse=True):
category_name = category_map[cat_item["norm"].upper()]
items_below = [item for item in text_items if item["y"] < cat_item["y"] - row_tolerance]
if not items_below:
print(f"\n{category_name}: 아래에 텍스트 없음")
continue
rows = _cluster_by_y(items_below, row_tolerance)
sorted_rows = sorted(rows, key=lambda x: x["y"], reverse=True)
first_below_item = max(items_below, key=lambda x: x["y"])
header_start_y = first_below_item["y"]
# 2줄 헤더를 위해 더 넓은 범위 확인
header_merge_tolerance = row_tolerance * 4.0 # 더 넓게
header_candidate_rows = [row for row in sorted_rows if header_start_y - header_merge_tolerance <= row["y"] <= header_start_y + row_tolerance]
print(f"\n{'=' * 80}")
print(f"{category_name} - 헤더 영역 텍스트 (Y={header_start_y:.2f} 기준, 범위 ±{header_merge_tolerance:.2f}):")
print(f"{'=' * 80}")
# Y 좌표별로 그룹핑해서 출력
y_groups = {}
for row in header_candidate_rows:
y_key = round(row["y"], 2)
if y_key not in y_groups:
y_groups[y_key] = []
for item in row["items"]:
y_groups[y_key].append(item)
for y_val in sorted(y_groups.keys(), reverse=True):
print(f"\n [Y={y_val:.2f}]")
items = sorted(y_groups[y_val], key=lambda x: x["x"])
for item in items:
print(f" '{item['norm']}' @ X={item['x']:.2f}")