# -*- coding: utf-8 -*-
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager as fm
import arabic_reshaper
from bidi.algorithm import get_display

# Persian font
FP = r"C:\Windows\Fonts\tahoma.ttf"
fm.fontManager.addfont(FP)
TAHOMA = fm.FontProperties(fname=FP)
plt.rcParams["font.family"] = TAHOMA.get_name()
plt.rcParams["axes.unicode_minus"] = False

NAVY = "#1F3864"; BLUE = "#2E5496"; TEAL = "#2E8B8B"; ORANGE = "#D98C2B"; RED = "#B5453B"; GREY = "#9AA5B1"

def fa(s):
    return get_display(arabic_reshaper.reshape(str(s)))

# ---------- Chart 1: Global market growth ----------
fig, ax = plt.subplots(figsize=(7.2, 3.5), dpi=150)
years = ["2024", "2025", "2030", "2033", "2035"]
peat = [4.62, 4.86, 5.34, 6.40, 7.10]
gm   = [5.28, 5.63, 7.30, 8.20, 8.86]
x = range(len(years))
ax.plot(x, peat, marker="o", lw=2.6, color=BLUE, label=fa("بازار جهانی پیت (میلیارد دلار)"))
ax.plot(x, gm, marker="s", lw=2.6, color=TEAL, ls="--", label=fa("بازار بسترهای کشت (میلیارد دلار)"))
for i, v in enumerate(peat):
    ax.annotate(f"{v:.1f}", (i, v), textcoords="offset points", xytext=(0, 8), ha="center", fontproperties=TAHOMA, fontsize=8, color=NAVY)
ax.set_xticks(list(x)); ax.set_xticklabels(years, fontproperties=TAHOMA)
ax.set_title(fa("رشد بازار جهانی پیت و بسترهای کشت (۲۰۲۴ تا ۲۰۳۵)"), fontproperties=TAHOMA, fontsize=12, color=NAVY, pad=10)
ax.set_ylabel(fa("میلیارد دلار"), fontproperties=TAHOMA, fontsize=9)
ax.legend(prop=TAHOMA, fontsize=8, loc="upper left", frameon=False)
ax.grid(axis="y", ls=":", alpha=0.5); ax.set_ylim(0, 10)
for s in ["top", "right"]: ax.spines[s].set_visible(False)
ax.annotate(fa("CAGR ≈ ۴٫۵٪–۶٪"), (3.0, 5.2), fontproperties=TAHOMA, fontsize=9, color=ORANGE, weight="bold")
plt.tight_layout(); plt.savefig("chart_market.png", bbox_inches="tight"); plt.close()

# ---------- Chart 2: Environmental impact ----------
fig, ax = plt.subplots(figsize=(7.2, 3.4), dpi=150)
subs = [fa("خاک پیت"), fa("پشم معدنی"), fa("کوکوپیت")]
mpt = [6.79, 10.6, 48.51]
co2 = [20.2, 32.1, 47.0]
cols = [TEAL, GREY, RED]
xp = range(len(subs))
bars = ax.bar(xp, mpt, color=cols, width=0.55)
for i, v in enumerate(mpt):
    ax.text(i, v + 0.8, f"{v}", ha="center", fontproperties=TAHOMA, fontsize=9, color=NAVY, weight="bold")
ax.set_xticks(list(xp)); ax.set_xticklabels(subs, fontproperties=TAHOMA, fontsize=10)
ax.set_ylabel(fa("اثر زیست‌محیطی (mPt)"), fontproperties=TAHOMA, fontsize=9)
ax.set_title(fa("اثر زیست‌محیطی بسترهای کشت — پیت کمترین اثر را دارد"), fontproperties=TAHOMA, fontsize=12, color=NAVY, pad=10)
ax.grid(axis="y", ls=":", alpha=0.5)
for s in ["top", "right"]: ax.spines[s].set_visible(False)
ax.annotate(fa("۷ برابر کمتر از کوکوپیت"), (0.05, 30), fontproperties=TAHOMA, fontsize=9.5, color=TEAL, weight="bold")
plt.tight_layout(); plt.savefig("chart_env.png", bbox_inches="tight"); plt.close()

# ---------- Chart 3: CAPEX structure (donut) ----------
fig, ax = plt.subplots(figsize=(6.4, 3.9), dpi=150)
labels = ["ماشین‌آلات و خط فرآوری", "سیستم بسته‌بندی", "ساختمان و سالن تولید",
          "وسایل حمل‌ونقل", "تأسیسات و سردخانه", "زمین، محوطه و سایر"]
vals = [80, 50, 25, 12, 9, 9]
cols = [BLUE, TEAL, NAVY, ORANGE, "#6FA8C7", GREY]
w, _ = ax.pie(vals, colors=cols, startangle=90, counterclock=False,
              wedgeprops=dict(width=0.42, edgecolor="white", linewidth=1.5))
ax.legend([f"{fa(l)} — {v}" for l, v in zip(labels, vals)], prop=TAHOMA, fontsize=8.5,
          loc="center left", bbox_to_anchor=(0.92, 0.5), frameon=False)
ax.text(0, 0.12, fa("≈ ۱۸۵"), ha="center", fontproperties=TAHOMA, fontsize=15, color=NAVY, weight="bold")
ax.text(0, -0.16, fa("میلیارد تومان"), ha="center", fontproperties=TAHOMA, fontsize=9, color=NAVY)
ax.set_title(fa("ساختار سرمایهٔ ثابت طرح (ارقام شاخصی، میلیارد تومان)"), fontproperties=TAHOMA, fontsize=11.5, color=NAVY, pad=8)
plt.tight_layout(); plt.savefig("chart_capex.png", bbox_inches="tight"); plt.close()

# ---------- Chart 4: Cumulative cash flow / payback ----------
fig, ax = plt.subplots(figsize=(7.2, 3.5), dpi=150)
yrs = list(range(0, 11))
# illustrative indexed cumulative cash flow (study reports very fast payback)
cum = [-210, 60, 360, 700, 1080, 1500, 1960, 2460, 3000, 3580, 4200]
ax.axhline(0, color="#888", lw=1)
ax.plot(yrs, cum, marker="o", lw=2.6, color=BLUE)
ax.fill_between(yrs, cum, 0, where=[c >= 0 for c in cum], color=TEAL, alpha=0.18)
ax.fill_between(yrs, cum, 0, where=[c < 0 for c in cum], color=RED, alpha=0.18)
ax.set_xticks(yrs); ax.set_xticklabels([fa(f"سال {y}") for y in yrs], fontproperties=TAHOMA, fontsize=7.5, rotation=0)
ax.set_ylabel(fa("جریان نقدی تجمعی (میلیارد تومان، شاخصی)"), fontproperties=TAHOMA, fontsize=8.5)
ax.set_title(fa("جریان نقدی تجمعی و بازگشت سرمایه"), fontproperties=TAHOMA, fontsize=12, color=NAVY, pad=10)
ax.grid(axis="y", ls=":", alpha=0.5)
for s in ["top", "right"]: ax.spines[s].set_visible(False)
ax.annotate(fa("بازگشت سرمایه در سال نخست"), (0.6, 250), fontproperties=TAHOMA, fontsize=9, color=ORANGE, weight="bold",
            xytext=(2.0, -120), textcoords="data",
            arrowprops=dict(arrowstyle="->", color=ORANGE))
plt.tight_layout(); plt.savefig("chart_cashflow.png", bbox_inches="tight"); plt.close()

print("charts done")
