"""
diesel_engine_analysis.py
==========================
Analysis & visualization toolkit for the "Developing a Diesel Engine to Work
with Different Types of Fuels" research project (Kafr El-Sheikh University).

Author: Mohamed Ahmed
Repository: diesel-engine-alternative-fuels

This script reproduces the engine performance and emissions analysis for:
    - Pure Diesel (B0)
    - 20% Biodiesel blend (B20)
    - B20 + Magnetic fuel conditioning
    - B20 + Magnetic conditioning + Nano-additive

Usage:
    python diesel_engine_analysis.py
"""

import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path

DATA_DIR = Path(__file__).parent / "data"
OUT_DIR = Path(__file__).parent / "output_charts"
OUT_DIR.mkdir(exist_ok=True)


def load_data():
    """Load performance and emissions datasets."""
    performance = pd.read_csv(DATA_DIR / "performance_data.csv")
    emissions = pd.read_csv(DATA_DIR / "emissions_data.csv")
    return performance, emissions


def compute_efficiency_gain(performance: pd.DataFrame) -> pd.DataFrame:
    """Compute % efficiency improvement of each blend vs baseline diesel at full load."""
    full_load = performance[performance["power_kW"] == 4.5]
    baseline = full_load.loc[full_load.fuel_type == "Diesel(B0)", "efficiency_pct"].values[0]
    full_load = full_load.copy()
    full_load["efficiency_gain_pct"] = (
        (full_load["efficiency_pct"] - baseline) / baseline * 100
    )
    return full_load[["fuel_type", "efficiency_pct", "efficiency_gain_pct"]]


def plot_efficiency_curves(performance: pd.DataFrame):
    """Plot efficiency vs power for all fuel blends."""
    fig, ax = plt.subplots(figsize=(8, 5))
    for fuel, group in performance.groupby("fuel_type"):
        group = group.sort_values("power_kW")
        ax.plot(group["power_kW"], group["efficiency_pct"], marker="o", label=fuel)
    ax.set_xlabel("Engine Power (kW)")
    ax.set_ylabel("Thermal Efficiency (%)")
    ax.set_title("Engine Efficiency vs Power for Different Fuel Blends")
    ax.legend()
    ax.grid(alpha=0.3)
    fig.tight_layout()
    fig.savefig(OUT_DIR / "efficiency_vs_power.png", dpi=150)
    plt.close(fig)


def plot_emissions(emissions: pd.DataFrame):
    """Plot NOx and CO emissions vs power for diesel vs B20."""
    fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
    for fuel, group in emissions.groupby("fuel_type"):
        group = group.sort_values("power_W")
        axes[0].plot(group["power_W"], group["NOx_ppm"], marker="o", label=fuel)
        axes[1].plot(group["power_W"], group["CO_ppm"], marker="s", label=fuel)

    axes[0].set_title("NOx Emissions vs Power")
    axes[0].set_xlabel("Power (W)")
    axes[0].set_ylabel("NOx (ppm)")
    axes[0].legend()
    axes[0].grid(alpha=0.3)

    axes[1].set_title("CO Emissions vs Power")
    axes[1].set_xlabel("Power (W)")
    axes[1].set_ylabel("CO (ppm)")
    axes[1].legend()
    axes[1].grid(alpha=0.3)

    fig.tight_layout()
    fig.savefig(OUT_DIR / "emissions_comparison.png", dpi=150)
    plt.close(fig)


def air_fuel_ratio(mass_flow_air_gs: float, mass_flow_fuel_gs: float) -> float:
    """Calculate Air-to-Fuel ratio (A/F)."""
    return mass_flow_air_gs / mass_flow_fuel_gs


def engine_efficiency(power_kW: float, mass_flow_fuel_gs: float, heating_value_kJkg: float = 45000) -> float:
    """
    Calculate thermal efficiency (%) of the engine.
    power_kW           : brake power output (kW)
    mass_flow_fuel_gs  : fuel mass flow rate (g/s)
    heating_value_kJkg : lower heating value of fuel (kJ/kg), diesel ~45000
    """
    fuel_flow_kg_s = mass_flow_fuel_gs / 1000
    fuel_power_kW = fuel_flow_kg_s * heating_value_kJkg
    return (power_kW / fuel_power_kW) * 100 if fuel_power_kW else 0


if __name__ == "__main__":
    performance, emissions = load_data()

    print("=== Efficiency Gain at Full Load (4.5 kW) vs Pure Diesel ===")
    print(compute_efficiency_gain(performance).to_string(index=False))

    plot_efficiency_curves(performance)
    plot_emissions(emissions)

    print("\nCharts saved to:", OUT_DIR.resolve())

    # Example manual calculation (from lab measurement, Chapter 3)
    af_ratio = air_fuel_ratio(mass_flow_air_gs=6.0, mass_flow_fuel_gs=0.41)
    eff = engine_efficiency(power_kW=0.9, mass_flow_fuel_gs=0.41)
    print(f"\nExample A/F ratio: {af_ratio:.2f}")
    print(f"Example engine efficiency: {eff:.2f}%")
