"""AI Assignment 1 — exploratory analysis of the Heart UCI dataset.

Run with: python assignment.py
"""

from pathlib import Path

import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt
import pandas as pd


URL = "https://raw.githubusercontent.com/sharmaroshan/Heart-UCI-Dataset/master/heart.csv"
OUTPUT_DIR = Path(__file__).parent / "assets"


def prepare_chart() -> None:
    """Apply one consistent, readable style to all assignment figures."""
    plt.rcParams.update(
        {
            "figure.figsize": (8.4, 5.2),
            "figure.facecolor": "#ffffff",
            "axes.facecolor": "#fbfaf7",
            "axes.edgecolor": "#d8d5ce",
            "axes.labelcolor": "#243247",
            "axes.titlecolor": "#132238",
            "axes.titleweight": "bold",
            "axes.grid": True,
            "grid.color": "#e8e5de",
            "grid.linewidth": 0.8,
            "grid.alpha": 0.8,
            "font.family": "DejaVu Sans",
            "font.size": 10,
            "xtick.color": "#5d6878",
            "ytick.color": "#5d6878",
        }
    )


def save_current_figure(filename: str) -> None:
    """Save a web-ready copy of the current Matplotlib figure."""
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    plt.tight_layout()
    plt.savefig(OUTPUT_DIR / filename, dpi=180, bbox_inches="tight")
    plt.close()


def main() -> None:
    # Load the Heart UCI dataset directly from its GitHub repository.
    data = pd.read_csv(URL)

    # Preview the first ten patients to understand the table structure.
    print("FIRST 10 ROWS")
    print(data.head(n=10).to_string(index=False))

    # The shape gives the number of rows and columns: (303, 14).
    print("\nDATASET SHAPE")
    print(data.shape)

    # info() lists column names, data types, and non-null counts.
    print("\nDATASET INFORMATION")
    data.info()

    # describe() summarizes the numerical columns.
    print("\nDESCRIPTIVE STATISTICS")
    print(data.describe().round(2).to_string())

    prepare_chart()

    data["age"].hist(bins=6, color="#277a78", edgecolor="white")
    plt.xlabel("Age")
    plt.ylabel("Number of patients")
    plt.title("Age distribution")
    # Most patients are between 53 and 61 years old (104 patients).
    save_current_figure("age-distribution.png")

    data.boxplot(
        column="thalach",
        by="target",
        patch_artist=True,
        boxprops={"facecolor": "#bfe3dc", "color": "#277a78"},
        medianprops={"color": "#d45b3f", "linewidth": 2},
        whiskerprops={"color": "#277a78"},
        capprops={"color": "#277a78"},
    )
    plt.xlabel("Target")
    plt.ylabel("Maximum heart rate achieved (bpm)")
    plt.title("Maximum Heart Rate (thalach) by Target")
    plt.suptitle("")  # Remove the default automatic title added by boxplot().
    # Target 1 has a higher median thalach (161 bpm) than Target 0 (142 bpm).
    save_current_figure("thalach-by-target.png")

    plt.scatter(
        data["age"],
        data["thalach"],
        c=data["target"],
        cmap="coolwarm",
        alpha=0.65,
        edgecolors="white",
        linewidths=0.35,
    )
    plt.xlabel("Age (years)")
    plt.ylabel("Maximum heart rate achieved (bpm)")
    plt.title("Age vs. Maximum Heart Rate, Colored by Target")
    # The moderate negative correlation (-0.40) means thalach tends to fall as age rises.
    save_current_figure("age-vs-thalach.png")

    data.boxplot(
        column="chol",
        by="target",
        patch_artist=True,
        boxprops={"facecolor": "#f5d6bc", "color": "#d45b3f"},
        medianprops={"color": "#277a78", "linewidth": 2},
        whiskerprops={"color": "#d45b3f"},
        capprops={"color": "#d45b3f"},
    )
    plt.xlabel("Target")
    plt.ylabel("Cholesterol (mg/dL)")
    plt.title("Cholesterol by Target")
    plt.suptitle("")  # Remove the default automatic title added by boxplot().
    # The two groups overlap strongly; Target 0 has a slightly higher median cholesterol.
    save_current_figure("cholesterol-by-target.png")


if __name__ == "__main__":
    main()
