# /// script
# requires-python = ">=3.10"
# dependencies = ["opencv-python==4.14.0.94"]
# ///
"""CIT RoboMaster S1 바로 시연: 노트북 카메라가 S1 위에 붙인 ArUco 마커를 따라 경로를 그립니다.

    uv run cit_s1_overhead_demo.py marker   # 붙일 마커(robot_marker_0.png)를 만듭니다. A4에 인쇄
    uv run cit_s1_overhead_demo.py          # 노트북 카메라로 마커 0번을 따라 초록 선을 그립니다
    uv run cit_s1_overhead_demo.py 1        # 외장 웹캠(1번 카메라)을 쓸 때

S1은 RoboMaster 앱(Lab 또는 조종 화면)으로 움직이고, 이 파일은 노트북에서 보기만 합니다.
처음 한 번은 인터넷이 되는 곳에서 실행해 uv가 패키지를 받아 두게 합니다.
영상 창에서 c 를 누르면 선을 지우고, q 를 누르면 끝납니다.
Source: https://citcoding.com/courses/robot-python/robomaster-s1/lab/
"""
import sys

import cv2

DICTIONARY = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
DETECTOR = cv2.aruco.ArucoDetector(DICTIONARY, cv2.aruco.DetectorParameters())


def make_marker():
    cv2.imwrite("robot_marker_0.png", cv2.aruco.generateImageMarker(DICTIONARY, 0, 400))
    print("robot_marker_0.png 를 저장했습니다. 흰 여백을 남기고 인쇄해 S1 위에 평평하게 붙입니다.")


def track(camera_index):
    cam = cv2.VideoCapture(camera_index)
    path = []
    try:
        while True:
            ok, frame = cam.read()
            if not ok:
                print("영상이 들어오지 않습니다. 카메라 번호를 확인하세요.")
                break
            corners, ids, _ = DETECTOR.detectMarkers(frame)
            if ids is not None:
                cv2.aruco.drawDetectedMarkers(frame, corners, ids)
                found = list(ids.flatten())
                if 0 in found:
                    pts = corners[found.index(0)][0]
                    path.append((int(pts[:, 0].mean()), int(pts[:, 1].mean())))
            for a, b in zip(path, path[1:]):
                cv2.line(frame, a, b, (0, 255, 0), 2)
            if path:
                cv2.putText(frame, f"S1 x={path[-1][0]} y={path[-1][1]}  points={len(path)}", (10, 30),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)
            cv2.imshow("S1 overhead  (c: clear, q: quit)", frame)
            key = cv2.waitKey(1) & 0xFF
            if key == ord("c"):
                path.clear()
            elif key == ord("q"):
                break
    finally:
        cam.release()
        cv2.destroyAllWindows()


def main():
    arg = sys.argv[1] if len(sys.argv) > 1 else "0"
    if arg == "marker":
        make_marker()
    elif arg.isdigit():
        track(int(arg))
    else:
        print(__doc__)


if __name__ == "__main__":
    main()
