import matplotlib
# 关键：设置无交互后端，适配 ideone 云端环境
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO

# 适配Linux环境中文字体
plt.rcParams["font.family"] = ["DejaVu Sans"]
plt.rcParams['axes.unicode_minus'] = False

cities = [
    "Nanning", "Liuzhou", "Guilin", "Wuzhou", "Beihai", "Fangchenggang", "Qinzhou",
    "Guigang", "Yulin", "Baise", "Hezhou", "Hechi", "Laibin", "Chongzuo"
]
out_contract = np.array([16.18, 31.03, 20.19, 0.64, 2.38, 0.25, 2.01,
                          5.16, 1.88, 0.29, 6.15, 4.92, 7.13, 1.11])
in_contract = np.array([162.52, 20.02, 6.89, 12.80, 4.66, 4.09, 57.62,
                          10.42, 13.73, 3.78, 1.66, 8.31, 6.69, 2.27])
total = out_contract + in_contract
finish_rate = np.array([46, 43, 46, 35, 5, 7, 70, 22, 22, 8, 30, 24, 36, 7])


def save_fig(name):
    buf = BytesIO()
    plt.tight_layout()
    plt.savefig(buf, format='png', dpi=100, bbox_inches="tight")
    print(f"{name}‑plot generated (bytes length: {len(buf.getvalue())})")
    buf.close()


# 1. Pie chart
plt.figure(figsize=(10, 10))
plt.pie(total, labels=cities, autopct="%.1f%%", startangle=90)
plt.title("City Total‑Contract Proportion")
save_fig("pie")
plt.close()

# 2. Group bar chart
x = np.arange(len(cities))
width = 0.35
plt.figure(figsize=(14, 7))
plt.bar(x - width/2, out_contract, width, label="Output Contract")
plt.bar(x + width/2, in_contract, width, label="Absorb Contract")
plt.xticks(x, cities, rotation=45, ha="right")
plt.xlabel("City")
plt.ylabel("Amount")
plt.title("Output & Absorb Contract Comparison")
plt.legend()
save_fig("bar_group")
plt.close()

# 3. Finish‑rate bar
plt.figure(figsize=(14, 7))
bars = plt.bar(cities, finish_rate)
plt.xticks(rotation=45, ha="right")
plt.ylabel("Finish‑rate %")
plt.title("City Task Completion Rate")
for bar in bars:
    h = bar.get_height()
    plt.text(bar.get_x() + bar.get_width() / 2, h, f"{h}%", ha="center", va="bottom")
save_fig("bar_rate")
plt.close()

print("All three charts have been rendered successfully.")