"""
Task 3: AI-assisted analysis and scientific plotting
Dataset: synthetic teaching data only (40 replicate pens)
Topic: dietary crude protein level and starter broiler growth performance

Required packages:
    pandas, numpy, scipy, matplotlib

Run:
    python Task3_肉鸡生长性能分析.py
"""
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

HERE = Path(__file__).resolve().parent
DATA_FILE = HERE / "Task3_肉鸡生长性能模拟数据.csv"
OUT_FIG = HERE / "Figure3_BWG_by_CP.png"
OUT_SUMMARY = HERE / "Task3_group_summary.csv"

df = pd.read_csv(DATA_FILE)

# Basic dataset checks (the file contains synthetic teaching records only).
if len(df) != 40:
    raise ValueError(f"Expected 40 synthetic records, found {len(df)}.")
if set(df["CP_pct"].unique()) != {20, 21, 22, 23}:
    raise ValueError("Unexpected CP levels; expected 20, 21, 22, and 23%.")
if not (df.groupby("CP_pct").size() == 10).all():
    raise ValueError("Each CP group should contain 10 records.")
if not (df["AME_kcal_kg"] == 2900).all():
    raise ValueError("AME should be fixed at 2900 kcal/kg in this teaching dataset.")

required_columns = [
    "CP_pct", "AME_kcal_kg", "Initial_BW_g_bird", "BWG_g_bird",
    "Feed_Intake_g_bird", "FCR", "Final_BW_g_bird"
]
missing = [col for col in required_columns if col not in df.columns]
if missing:
    raise ValueError(f"Missing required columns: {missing}")

# Formula check: FCR is feed intake divided by body weight gain.
fcr_calculated = df["Feed_Intake_g_bird"] / df["BWG_g_bird"]
if not np.allclose(fcr_calculated, df["FCR"], atol=0.00005):
    raise ValueError("FCR check failed. Please verify the FCR formula.")
final_bw_calculated = df["Initial_BW_g_bird"] + df["BWG_g_bird"]
if not np.allclose(final_bw_calculated, df["Final_BW_g_bird"], atol=0.0001):
    raise ValueError("Final body weight check failed.")

# Analysis 1: descriptive statistics by dietary CP level.
summary = (
    df.groupby("CP_pct")
      .agg(
          n=("BWG_g_bird", "count"),
          BWG_mean=("BWG_g_bird", "mean"),
          BWG_sd=("BWG_g_bird", "std"),
          FI_mean=("Feed_Intake_g_bird", "mean"),
          FCR_mean=("FCR", "mean"),
          FinalBW_mean=("Final_BW_g_bird", "mean")
      )
      .reset_index()
)
summary.to_csv(OUT_SUMMARY, index=False, encoding="utf-8-sig")

# Analysis 2: one-way ANOVA for body weight gain across CP groups.
cp_levels = sorted(df["CP_pct"].unique())
groups = [df.loc[df["CP_pct"] == cp, "BWG_g_bird"].to_numpy()
          for cp in cp_levels]
anova_result = stats.f_oneway(*groups)

# Tukey HSD-style all-pair comparison after the omnibus ANOVA.
tukey_result = stats.tukey_hsd(*groups)

# Analysis 3: Pearson correlation between feed intake and body weight gain.
correlation_result = stats.pearsonr(
    df["Feed_Intake_g_bird"], df["BWG_g_bird"]
)

# English scientific plot: group mean +/- SEM.
means = summary["BWG_mean"].to_numpy()
sems = (summary["BWG_sd"] / np.sqrt(summary["n"])).to_numpy()
x = np.arange(len(cp_levels))

fig, ax = plt.subplots(figsize=(8.4, 5.2), dpi=180)
ax.bar(x, means, yerr=sems, capsize=5, label="Mean +/- SEM")
ax.set_xticks(x, [f"{cp}%" for cp in cp_levels])
ax.set_xlabel("Dietary crude protein level (%)")
ax.set_ylabel("Body weight gain (g/bird)")
ax.set_title("Body Weight Gain by Dietary Crude Protein Level")
ax.legend(frameon=False)
ax.grid(axis="y", alpha=0.25)
fig.text(0.5, 0.015, "Synthetic teaching data; n = 10 records per group. Not measured animal data.",
         ha="center", fontsize=8)
fig.tight_layout(rect=[0, 0.04, 1, 1])
fig.savefig(OUT_FIG, bbox_inches="tight")
plt.close(fig)

print("Data check passed: 40 fixed synthetic records; 10 records per CP group; AME = 2900 kcal/kg.")
print("Group summary:")
print(summary.round(3).to_string(index=False))
print(f"\nOne-way ANOVA: F={anova_result.statistic:.3f}, "
      f"p={anova_result.pvalue:.4g}")
print("Note: group differences were built into the teaching dataset; p-values are for workflow demonstration only.")
print(f"Pooled Pearson correlation (all CP groups combined): r={correlation_result.statistic:.3f}, "
      f"p={correlation_result.pvalue:.4g}")
print("Note: this pooled correlation is not adjusted for CP group and may partly reflect between-group differences.")
print("\nTukey pairwise p-values (group order follows CP levels):")
print(np.array2string(tukey_result.pvalue, precision=4))
print(f"\nFigure saved to: {OUT_FIG.name}")
