import matplotlib.pyplot as plt
import numpy as np

# 한글 폰트 및 마이너스 기호 깨짐 방지 설정
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['axes.unicode_minus'] = False

# 1. 시간 범위 설정 (예: 0일부터 8일까지)
t = np.linspace(0, 8, 400)

# 2. 식물의 생장량 함수 f(t) 정의 (3차 함수 모델)
# f(t) = -t^3 + 9t^2 + 12t (단위: cm)
# 초기에는 천천히 자라다가 속도가 붙은 뒤 완만해지는 S자 곡선의 형태를 일부 모사합니다.
f_t = -(t**3) + 9 * (t**2) + 12 * t

# 3. 도함수 f'(t) 정의 (순간 성장 속도, 2차 함수)
# f'(t) = -3t^2 + 18t + 12
f_prime_t = -3 * (t**2) + 18 * t + 12

# 4. 성장이 가장 빠른 시점(도함수의 꼭짓점, 즉 2차함수 대칭축 공식 t = -b / 2a) 계산
# -3t^2 + 18t + 12 에서 a = -3, b = 18 이므로 t = -18 / (2 * -3) = 3
t_max_growth = 3.0
max_growth_rate = -3 * (t_max_growth**2) + 18 * t_max_growth + 12
max_height = -(t_max_growth**3) + 9 * (t_max_growth**2) + 12 * t_max_growth

# 결과 출력
print(
    f'[수학적 모델링 분석 결과]\n'
    f'- 식물이 가장 폭발적으로 자라는 시점: t = {t_max_growth}일\n'
    f'- 이때의 최대 순간 성장 속도: {max_growth_rate} cm/일\n'
    f'- 이때의 식물 높이: {max_height} cm'
)

# 5. 그래프 시각화 (위: 원함수 / 아래: 도함수)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), sharex=True)

# (1) 원함수 그래프: 시간(t)에 따른 식물의 높이 f(t)
ax1.plot(
    t, f_t, label='Plant Height f(t)', color='forestgreen', linewidth=2.5
)
ax1.axvline(
    x=t_max_growth,
    color='orange',
    linestyle='--',
    label=f'Max Growth Time (t={t_max_growth})',
)
ax1.set_ylabel('Plant Height (cm)', fontsize=12)
ax1.set_title(
    "Math II Application: Plant Growth & Derivative Model", fontsize=14
)
ax1.grid(True, linestyle=':', alpha=0.7)
ax1.legend(loc='upper left')

# (2) 도함수 그래프: 시간(t)에 따른 순간 성장 속도 f'(t)
ax2.plot(
    t,
    f_prime_t,
    label="Growth Rate f'(t)",
    color='dodgerblue',
    linewidth=2.5,
)
ax2.scatter(
    [t_max_growth],
    [max_growth_rate],
    color='red',
    zorder=5,
    s=80,
    label=f'Max Growth Rate ({max_growth_rate} cm/day)',
)
ax2.axvline(x=t_max_growth, color='orange', linestyle='--')
ax2.set_xlabel('Time t (days)', fontsize=12)
ax2.set_ylabel('Growth Rate (cm/day)', fontsize=12)
ax2.grid(True, linestyle=':', alpha=0.7)
ax2.legend(loc='upper right')

plt.tight_layout()
plt.show()
