"""
SAMPLE research project: study hours and test scores (SYNTHETIC DATA)

The 60 records are generated by this script with a fixed random seed.
They are NOT real students. The data was built with a relationship between
study hours and score, so the result shows how the method works, not a
real-world finding.

How to run:
    pip install numpy matplotlib
    python analysis.py

It writes sample-data-synthetic.csv and two chart PNG files into the
current folder.
"""
import csv

import numpy as np
import matplotlib

matplotlib.use("Agg")  # draw to files, no window needed
import matplotlib.pyplot as plt

INK, ACCENT, LIGHT = "#0f172a", "#0891b2", "#67e8f9"


def make_data(n=60, seed=42):
    """Create synthetic study hours (per day) and test scores (0-100)."""
    rng = np.random.default_rng(seed)
    hours = np.round(rng.uniform(0.5, 5.0, n), 1)
    noise = rng.normal(0, 7, n)
    scores = np.clip(np.round(45 + 8 * hours + noise), 0, 100)
    return hours, scores


def save_csv(hours, scores, path="sample-data-synthetic.csv"):
    with open(path, "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["record_id", "study_hours_per_day", "test_score"])
        for i, (h, s) in enumerate(zip(hours, scores), start=1):
            writer.writerow([f"R{i:02d}", h, int(s)])


def summarise(hours, scores):
    """Summary statistics, correlation, a straight-line fit and group means."""
    r = float(np.corrcoef(hours, scores)[0, 1])
    slope, intercept = np.polyfit(hours, scores, 1)
    bands = [
        ("Under 2 h", hours < 2),
        ("2 to 3.5 h", (hours >= 2) & (hours < 3.5)),
        ("3.5 h or more", hours >= 3.5),
    ]
    groups = [
        {"label": label, "n": int(mask.sum()), "mean": float(scores[mask].mean())}
        for label, mask in bands
    ]
    return {
        "n": int(len(hours)),
        "mean_hours": float(hours.mean()),
        "mean_score": float(scores.mean()),
        "r": r,
        "slope": float(slope),
        "intercept": float(intercept),
        "groups": groups,
    }


def chart_scatter(hours, scores, stats, path="study-hours-vs-score.png"):
    fig, ax = plt.subplots(figsize=(8, 4.6), dpi=150)
    ax.scatter(hours, scores, s=34, color=ACCENT, alpha=0.8, edgecolor="white", linewidth=0.6)
    xs = np.linspace(hours.min(), hours.max(), 50)
    ax.plot(xs, stats["slope"] * xs + stats["intercept"], color=INK, linewidth=2,
            label=f"Straight-line fit (r = {stats['r']:.2f})")
    ax.set_xlabel("Study hours per day")
    ax.set_ylabel("Test score (out of 100)")
    ax.set_title("Study hours and test score (synthetic data, n = %d)" % stats["n"],
                 loc="left", fontsize=11, color=INK)
    ax.legend(frameon=False)
    ax.grid(alpha=0.25)
    for side in ("top", "right"):
        ax.spines[side].set_visible(False)
    fig.tight_layout()
    fig.savefig(path)
    plt.close(fig)


def chart_groups(stats, path="average-score-by-group.png"):
    fig, ax = plt.subplots(figsize=(8, 4.6), dpi=150)
    labels = [g["label"] for g in stats["groups"]]
    means = [g["mean"] for g in stats["groups"]]
    bars = ax.bar(labels, means, color=[LIGHT, ACCENT, INK], width=0.55)
    for bar, g in zip(bars, stats["groups"]):
        ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 1,
                f"{g['mean']:.1f}  (n = {g['n']})", ha="center", fontsize=10, color=INK)
    ax.set_ylim(0, 100)
    ax.set_xlabel("Study hours per day")
    ax.set_ylabel("Average test score")
    ax.set_title("Average score by study-hours group (synthetic data)",
                 loc="left", fontsize=11, color=INK)
    ax.grid(axis="y", alpha=0.25)
    for side in ("top", "right"):
        ax.spines[side].set_visible(False)
    fig.tight_layout()
    fig.savefig(path)
    plt.close(fig)


def run():
    hours, scores = make_data()
    save_csv(hours, scores)
    stats = summarise(hours, scores)
    chart_scatter(hours, scores, stats)
    chart_groups(stats)
    return stats


if __name__ == "__main__":
    s = run()
    print(f"Records: {s['n']}")
    print(f"Mean study hours: {s['mean_hours']:.2f}   Mean score: {s['mean_score']:.1f}")
    print(f"Correlation r = {s['r']:.2f}")
    print(f"Straight-line fit: score = {s['intercept']:.1f} + {s['slope']:.1f} x hours")
    for g in s["groups"]:
        print(f"  {g['label']:>14}: n = {g['n']:>2}, average score = {g['mean']:.1f}")
