"""
RoboDK API로 용접 경로 생성 방식 분석
- 실행 중인 RoboDK에 연결
- 예제 용접 파일 로드
- Weld Follow Project 기능 분석
- 경로 점들이 어떻게 생성되는지 추출
"""
from robodk.robolink import Robolink, ITEM_TYPE_PROGRAM, ITEM_TYPE_TARGET, ITEM_TYPE_FRAME
from robodk.robomath import *
import json, os

RDK = Robolink()  # 실행 중인 RoboDK에 연결

print("=== RoboDK 연결 ===")
print(f"  버전: {RDK.Version()}")
print(f"  스테이션: {RDK.ActiveStation().Name()}")

# ─── 현재 아이템 목록 ───
print("\n=== 현재 스테이션 아이템 ===")
items = RDK.ItemList()
for it in items:
    try:
        print(f"  [{it.type()}] {it.Name()}")
    except:
        pass

# ─── 예제 용접 파일 로드 시도 ───
EXAMPLE = r"E:\RoboDK\Library\04-Robot arc welding - CFP\Welding-with-Fanuc-ARC-Mate-120iB-10L-02.rdk"
if os.path.exists(EXAMPLE):
    print(f"\n=== 예제 파일 로드: {EXAMPLE} ===")
    RDK.AddFile(EXAMPLE)
    import time; time.sleep(3)
else:
    print(f"\n  예제 파일 없음: {EXAMPLE}")

# ─── 로드 후 아이템 목록 ───
print("\n=== 로드 후 스테이션 아이템 ===")
items = RDK.ItemList()
for it in items:
    try:
        t = it.type()
        name = it.Name()
        print(f"  [{t}] {name}")
    except Exception as e:
        print(f"  [ERR] {e}")

# ─── 프로그램(용접 경로) 찾기 ───
print("\n=== 프로그램/타겟 분석 ===")
programs = RDK.ItemList(ITEM_TYPE_PROGRAM)
for prog in programs:
    print(f"\n  프로그램: {prog.Name()}")
    # 프로그램 내 명령 가져오기
    try:
        instr_count = prog.InstructionCount()
        print(f"    명령 수: {instr_count}")
        for i in range(min(instr_count, 20)):
            name, instype, movetype, isjointtarget, pose, joints = prog.Instruction(i)
            print(f"    [{i}] {name} | movetype={movetype} | joint={isjointtarget}")
            if pose is not None:
                pos = pose.Pos()
                print(f"         위치: x={pos[0]:.1f} y={pos[1]:.1f} z={pos[2]:.1f}")
    except Exception as e:
        print(f"    ERR: {e}")

# ─── 타겟(경로 점) 분석 ───
print("\n=== 타겟(경로 점) 분석 ===")
targets = RDK.ItemList(ITEM_TYPE_TARGET)
print(f"  총 타겟: {len(targets)}개")
for t in targets[:10]:
    try:
        pose = t.Pose()
        pos = pose.Pos()
        print(f"  [{t.Name()}] x={pos[0]:.1f} y={pos[1]:.1f} z={pos[2]:.1f}")
    except Exception as e:
        print(f"  ERR: {e}")

# ─── 결과 저장 ───
result = {
    "version": str(RDK.Version()),
    "programs": [],
    "targets": []
}

for prog in programs:
    p = {"name": prog.Name(), "instructions": []}
    try:
        for i in range(prog.InstructionCount()):
            name, instype, movetype, isjointtarget, pose, joints = prog.Instruction(i)
            entry = {"name": name, "movetype": movetype, "isjoint": isjointtarget}
            if pose is not None:
                pos = pose.Pos()
                entry["pos"] = [round(pos[0],2), round(pos[1],2), round(pos[2],2)]
            p["instructions"].append(entry)
    except:
        pass
    result["programs"].append(p)

for t in targets:
    try:
        pose = t.Pose()
        pos = pose.Pos()
        result["targets"].append({"name": t.Name(), "pos": [round(pos[0],2), round(pos[1],2), round(pos[2],2)]})
    except:
        pass

OUT = r"E:\도진팩토리\3D스캔및티칭시스템\robodk_analysis.json"
with open(OUT, "w", encoding="utf-8") as f:
    json.dump(result, f, ensure_ascii=False, indent=2)
print(f"\n분석 결과 저장: {OUT}")
