#!/usr/bin/env python3
"""Plot Phase 3 external aerodynamics results: Cd and Cs vs yaw angle."""
import csv
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

basedir = os.path.dirname(os.path.abspath(__file__))
csv_path = os.path.join(basedir, "results.csv")

yaw, Cd, Cs, CmYaw = [], [], [], []
with open(csv_path) as f:
    reader = csv.DictReader(f)
    for row in reader:
        yaw.append(float(row['yaw_deg']))
        Cd.append(float(row['Cd']))
        Cs.append(float(row['Cs']))
        CmYaw.append(float(row['CmYaw']))

fig, axes = plt.subplots(1, 3, figsize=(15, 5))

# Cd vs yaw
ax = axes[0]
ax.plot(yaw, Cd, 'bo-', linewidth=2, markersize=8)
ax.set_xlabel('Yaw Angle (deg)', fontsize=12)
ax.set_ylabel('Drag Coefficient Cd', fontsize=12)
ax.set_title('Drag Coefficient vs Yaw Angle', fontsize=13)
ax.grid(True, alpha=0.3)
ax.set_xlim(-1, 21)

# Cs vs yaw
ax = axes[1]
ax.plot(yaw, Cs, 'rs-', linewidth=2, markersize=8)
ax.set_xlabel('Yaw Angle (deg)', fontsize=12)
ax.set_ylabel('Side Force Coefficient Cs', fontsize=12)
ax.set_title('Side Force Coefficient vs Yaw Angle', fontsize=13)
ax.grid(True, alpha=0.3)
ax.set_xlim(-1, 21)

# CmYaw vs yaw
ax = axes[2]
ax.plot(yaw, CmYaw, 'g^-', linewidth=2, markersize=8)
ax.set_xlabel('Yaw Angle (deg)', fontsize=12)
ax.set_ylabel('Yaw Moment Coefficient CmYaw', fontsize=12)
ax.set_title('Yaw Moment vs Yaw Angle', fontsize=13)
ax.grid(True, alpha=0.3)
ax.set_xlim(-1, 21)

fig.suptitle('Phase 3: External Aerodynamics - Canfly Drone Body\n'
             '(92mm dia x 163mm cylinder, V=10 m/s, kOmegaSST)',
             fontsize=14, fontweight='bold', y=1.02)
plt.tight_layout()
plot_path = os.path.join(basedir, "phase3_results.png")
plt.savefig(plot_path, dpi=150, bbox_inches='tight')
print(f"Plot saved to {plot_path}")

# Also print a summary table
print("\n" + "="*70)
print("Phase 3 External Aerodynamics Summary")
print("="*70)
print(f"{'Yaw (deg)':>10s}  {'Cd':>8s}  {'Cs':>8s}  {'CmYaw':>10s}")
print("-"*40)
for i in range(len(yaw)):
    print(f"{yaw[i]:10.0f}  {Cd[i]:8.4f}  {Cs[i]:8.4f}  {CmYaw[i]:10.4f}")
print("-"*40)
print(f"\nReference conditions:")
print(f"  Freestream velocity: 10 m/s")
print(f"  Reference area (frontal): 0.006648 m^2")
print(f"  Reference length (diameter): 0.092 m")
print(f"  Turbulence model: k-omega SST")
print(f"  Re_D = {10*0.092/1.516e-5:.0f}")
