# ======================================================================
# 12회차 | 09 발표 도우미 - 시도 기록 요약 (드론 없이)
# ----------------------------------------------------------------------
# 시도기록.csv 에서 우리 조의 기록만 모아서 발표에 쓸 내용을 정리해 준다.
# matplotlib 가 있으면 "시도할수록 얼마나 좋아졌나" 그래프도 그려서 저장한다.
#
# 3분 발표 틀
#   1. 우리 미션과 계획 (종이 설계 그림 보여 주기)
#   2. 첫 시도 결과 (몇 cm 떨어졌나, 왜 그랬을까)
#   3. 바꾼 것과 그 이유 (한 번에 하나씩!)
#   4. 최종 결과 (그래프)
#   5. 시간이 더 있으면 해 보고 싶은 것
# ======================================================================

import csv
import os

LOG_FILE = "시도기록.csv"

if not os.path.exists(LOG_FILE):
    raise SystemExit("시도기록.csv 가 없습니다.")

with open(LOG_FILE, encoding="utf-8-sig") as f:
    rows = list(csv.DictReader(f))

teams = sorted({r["조"] for r in rows})
print("기록이 있는 조 :", ", ".join(teams))
team = input("우리 조 이름 : ").strip() or (teams[0] if teams else "")
mine = [r for r in rows if r["조"] == team]
if not mine:
    raise SystemExit(f"{team} 의 기록이 없습니다.")

print()
print(f"===== {team} 발표 자료 =====")
dists = []
for r in mine:
    d = float(r["거리(cm)"])
    dists.append(d)
    print(f"{r['시도']}번째 : {d:5.0f}cm  박스 {'안' if r['박스 안'] == 'y' else '밖'}   바꾼 것 : {r['바꾼 것']}")
print()
print(f"첫 시도 {dists[0]:.0f}cm  ->  가장 좋은 시도 {min(dists):.0f}cm  ({dists[0] - min(dists):+.0f}cm 좋아짐)")
print(f"시도 {len(dists)}번")
print()
print("발표 틀")
print("  1. 우리 미션과 계획")
print(f"  2. 첫 시도 : {dists[0]:.0f}cm. 왜 그랬을까?")
print("  3. 바꾼 것 :", " / ".join(r["바꾼 것"] for r in mine[1:]) or "(없음)")
print(f"  4. 최종 결과 : {min(dists):.0f}cm")
print("  5. 더 해 보고 싶은 것")

try:
    import matplotlib.pyplot as plt
    plt.rcParams["font.family"] = "Malgun Gothic"
    plt.rcParams["axes.unicode_minus"] = False
    x = list(range(1, len(dists) + 1))
    plt.plot(x, dists, "o-")
    for xi, r in zip(x, mine):
        plt.annotate(r["바꾼 것"], (xi, float(r["거리(cm)"])), textcoords="offset points",
                     xytext=(0, 8), ha="center", fontsize=8)
    plt.xticks(x)
    plt.xlabel("시도")
    plt.ylabel("박스 가운데에서 거리 (cm)")
    plt.title(f"{team} - 시도할수록 얼마나 좋아졌나")
    plt.grid(alpha=0.3)
    plt.savefig(f"{team}_발표그래프.png", dpi=120)
    print(f"\n{team}_발표그래프.png 저장")
    plt.show()
except ImportError:
    print("(matplotlib 가 없어서 그래프는 생략)")
