#!/usr/bin/env python
# coding: utf-8
"""
Car Dataset Analysis
====================
Exploratory and explanatory analysis of 428 new-vehicle models (2004 US model
year): pricing, dealer margin, performance, fuel economy and segment mix by
origin, body type and drivetrain.

Method notes
------------
* Source file: Cars_Dataset.csv (432 lines incl. 4 fully blank separator rows,
  which are removed). 428 vehicle models remain.
* MSRP and Invoice are stored as text such as "$36,945 "; they are parsed to
  numbers (US dollars).
* Cylinders is blank for the two Mazda RX-8 variants. The RX-8 uses a Wankel
  rotary engine, which has no pistons/cylinders, so the value is kept as
  missing and the engine is flagged EngineType = "Rotary". Cylinder statistics
  therefore use 426 piston-engine models.
* No other field has missing values once the blank rows are removed.
* Two names repeat (Infiniti G35 4dr; Mercedes-Benz C240/C320 4dr): these are
  separate drivetrain variants (rear vs all-wheel drive) and are kept.
* The "+3 MPG" improvement is modelled as a scenario column (MPG_City_Plus3),
  so the reported MPG_City values stay as published.
* Fuel-cost assumptions (editable below): 15,000 miles per year, 55% city /
  45% highway driving (EPA combined weighting), US$1.88 per gallon
  (approximate 2004 US average for regular gasoline).

Usage:  python Car_Dataset_Analysis_Final.py [path/to/Cars_Dataset.csv] [outdir]
Requires: pandas, numpy; matplotlib (optional, for charts)
"""

import sys
from pathlib import Path

import numpy as np
import pandas as pd

# ---------------------------------------------------------------- settings
CSV_PATH = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("Cars_Dataset.csv")
OUT_DIR = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("car_outputs")
OUT_DIR.mkdir(parents=True, exist_ok=True)

MILES_PER_YEAR = 15_000
CITY_SHARE = 0.55
FUEL_PRICE = 1.88          # US$ per gallon
MPG_UPLIFT = 3             # scenario: +3 MPG city
HEAVY_LBS = 4_000          # weight threshold used for the heavy-vehicle filter

pd.set_option("display.width", 160)
pd.set_option("display.max_columns", 30)

# ---------------------------------------------------------------- 1. load
raw = pd.read_csv(CSV_PATH)
print(f"Raw shape: {raw.shape}")

# ---------------------------------------------------------------- 2. clean
car = raw.dropna(how="all").reset_index(drop=True)          # 4 separator rows
for col in ["MSRP", "Invoice"]:
    car[col] = (car[col].astype(str)
                .str.replace(r"[\$,\s]", "", regex=True)
                .astype(float))
for col in ["Make", "Model", "Type", "Origin", "DriveTrain"]:
    car[col] = car[col].str.strip()

car["EngineType"] = np.where(car["Cylinders"].isna(), "Rotary", "Piston")
print(f"Clean shape: {car.shape}")
print("Missing values after cleaning:\n", car.isna().sum()[car.isna().sum() > 0])

# ---------------------------------------------------------------- 3. features
car["DealerMargin"] = car["MSRP"] - car["Invoice"]
car["MarginPct"] = car["DealerMargin"] / car["MSRP"]
car["MPG_Combined"] = 1 / (CITY_SHARE / car["MPG_City"]
                           + (1 - CITY_SHARE) / car["MPG_Highway"])
car["AnnualFuelCost"] = MILES_PER_YEAR / car["MPG_Combined"] * FUEL_PRICE
car["HP_per_1000USD"] = car["Horsepower"] / (car["MSRP"] / 1000)
car["LbsPerHP"] = car["Weight"] / car["Horsepower"]
car["PriceBand"] = pd.cut(car["MSRP"],
                          [0, 20_000, 30_000, 40_000, 60_000, np.inf],
                          labels=["Under $20k", "$20-30k", "$30-40k", "$40-60k", "$60k+"])
car["IsHeavy"] = car["Weight"] > HEAVY_LBS
car["MPG_City_Plus3"] = car["MPG_City"] + MPG_UPLIFT

# ---------------------------------------------------------------- 4. profile
num_cols = ["MSRP", "Invoice", "DealerMargin", "MarginPct", "EngineSize",
            "Cylinders", "Horsepower", "MPG_City", "MPG_Highway", "Weight",
            "Wheelbase", "Length"]
summary = car[num_cols].describe().T
print("\nSummary statistics\n", summary.round(2))


def seg(by):
    return (car.groupby(by, observed=True)
            .agg(Models=("Model", "size"),
                 AvgMSRP=("MSRP", "mean"), MedianMSRP=("MSRP", "median"),
                 AvgMarginPct=("MarginPct", "mean"),
                 AvgHP=("Horsepower", "mean"),
                 AvgMPGCity=("MPG_City", "mean"),
                 AvgMPGHwy=("MPG_Highway", "mean"),
                 AvgWeight=("Weight", "mean"),
                 AvgFuelCost=("AnnualFuelCost", "mean"))
            .round(2))


by_origin, by_type, by_drive = seg("Origin"), seg("Type"), seg("DriveTrain")
by_band = seg("PriceBand")
print("\nBy origin\n", by_origin)
print("\nBy type\n", by_type)
print("\nBy drivetrain\n", by_drive)
print("\nOrigin x Type (count)\n", pd.crosstab(car["Origin"], car["Type"], margins=True))

makes = (car.groupby(["Make", "Origin"])
         .agg(Models=("Model", "size"), AvgMSRP=("MSRP", "mean"),
              AvgHP=("Horsepower", "mean"), AvgMPGCity=("MPG_City", "mean"),
              AvgMarginPct=("MarginPct", "mean"))
         .sort_values("Models", ascending=False).round(2))
print("\nTop 10 makes by number of models\n", makes.head(10))

# ---------------------------------------------------------------- 5. filters
asia = car[car["Origin"] == "Asia"]
europe = car[car["Origin"] == "Europe"]
asia_europe = car[car["Origin"].isin(["Asia", "Europe"])]
heavy = car[car["IsHeavy"]]
light = car[~car["IsHeavy"]]
print(f"\nAsia {len(asia)} | Europe {len(europe)} | Asia+Europe {len(asia_europe)}")
print(f"Heavy (> {HEAVY_LBS:,} lbs): {len(heavy)} | {HEAVY_LBS:,} lbs or less: {len(light)}")
print(heavy["Origin"].value_counts())

# ---------------------------------------------------------------- 6. drivers
corr = car[["MSRP", "EngineSize", "Cylinders", "Horsepower", "MPG_City",
            "MPG_Highway", "Weight", "Wheelbase", "Length"]].corr().round(3)
print("\nCorrelation matrix\n", corr)


def ols(y, X):
    """Ordinary least squares with intercept; returns coefficients and R²."""
    X1 = np.column_stack([np.ones(len(X)), X])
    beta, *_ = np.linalg.lstsq(X1, y, rcond=None)
    fitted = X1 @ beta
    r2 = 1 - ((y - fitted) ** 2).sum() / ((y - y.mean()) ** 2).sum()
    return beta, r2, fitted


# 6a. fuel economy: MPG_City ~ Weight + Horsepower (hybrids excluded)
ice = car[car["Type"] != "Hybrid"]
b_mpg, r2_mpg, _ = ols(ice["MPG_City"].values, ice[["Weight", "Horsepower"]].values)
print(f"\nMPG_City = {b_mpg[0]:.2f} {b_mpg[1]*1000:+.2f}/1000 lbs "
      f"{b_mpg[2]*100:+.2f}/100 hp   R² = {r2_mpg:.3f}")

# 6b. price: ln(MSRP) ~ HP + Weight + origin + type
#     reference segment = Asian sedan; HP per 100 hp, weight per 1,000 lbs
dummies = pd.get_dummies(car[["Origin", "Type"]]).astype(float)
dummies = dummies.drop(columns=["Origin_Asia", "Type_Sedan"])
Xp = np.column_stack([car["Horsepower"].values / 100, car["Weight"].values / 1000,
                      dummies.values])
b_px, r2_px, fit_px = ols(np.log(car["MSRP"].values), Xp)
names = ["Intercept", "Per +100 hp", "Per +1,000 lbs"] + list(dummies.columns)
price_model = pd.DataFrame({"Term": names, "Coef": b_px,
                            "Effect_pct": (np.exp(b_px) - 1) * 100})
price_model.loc[0, "Effect_pct"] = np.nan
print(f"\nln(MSRP) model R² = {r2_px:.3f}\n", price_model.round(4))
car["ModelPrice"] = np.exp(fit_px)
car["ValueGapPct"] = car["MSRP"] / car["ModelPrice"] - 1      # <0 = cheaper than spec implies
value_leaders = car.nsmallest(15, "ValueGapPct")[
    ["Make", "Model", "Type", "Origin", "MSRP", "ModelPrice", "ValueGapPct", "Horsepower"]]
print("\nBest value vs specification\n", value_leaders.round(3))

# ---------------------------------------------------------------- 7. scenario
base_cost = car["AnnualFuelCost"].mean()
mpg_comb_up = 1 / (CITY_SHARE / car["MPG_City_Plus3"]
                   + (1 - CITY_SHARE) / car["MPG_Highway"])
up_cost = (MILES_PER_YEAR / mpg_comb_up * FUEL_PRICE).mean()
print(f"\nScenario +{MPG_UPLIFT} MPG city: avg fuel cost ${base_cost:,.0f} -> "
      f"${up_cost:,.0f} per vehicle-year (saving ${base_cost-up_cost:,.0f})")

# ---------------------------------------------------------------- 8. export
car.to_csv(OUT_DIR / "cars_clean.csv", index=False)
with pd.ExcelWriter(OUT_DIR / "car_analysis_tables.xlsx") as xw:
    for name, df in {"summary": summary, "by_origin": by_origin, "by_type": by_type,
                     "by_drivetrain": by_drive, "by_priceband": by_band,
                     "makes": makes, "correlation": corr,
                     "price_model": price_model, "value_leaders": value_leaders}.items():
        df.to_excel(xw, sheet_name=name)

# ---------------------------------------------------------------- 9. charts
try:
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    pal = {"Asia": "#C8102E", "Europe": "#1F3A5F", "USA": "#E0A526"}

    fig, ax = plt.subplots(figsize=(8, 5))
    for o, g in car.groupby("Origin"):
        ax.scatter(g["Horsepower"], g["MSRP"] / 1000, s=18, alpha=.7, label=o, c=pal[o])
    ax.set(xlabel="Horsepower", ylabel="MSRP ($000)", title="Price rises with power")
    ax.legend(frameon=False); ax.spines[["top", "right"]].set_visible(False)
    fig.tight_layout(); fig.savefig(OUT_DIR / "price_vs_hp.png", dpi=200); plt.close(fig)

    fig, ax = plt.subplots(figsize=(6.5, 5.5))
    im = ax.imshow(corr.values, cmap="RdBu_r", vmin=-1, vmax=1)
    ax.set_xticks(range(len(corr)), corr.columns, rotation=45, ha="right")
    ax.set_yticks(range(len(corr)), corr.columns)
    for i in range(len(corr)):
        for j in range(len(corr)):
            v = corr.values[i, j]
            ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=7.5,
                    color="white" if abs(v) > .6 else "#222")
    fig.colorbar(im, ax=ax, shrink=.8); fig.tight_layout()
    fig.savefig(OUT_DIR / "correlation_heatmap.png", dpi=200); plt.close(fig)
    print(f"\nCharts saved to {OUT_DIR.resolve()}")
except ImportError:
    print("matplotlib not installed: charts skipped")
