"""TutorSyntax v26 regression comparison, aligned with Chapter 18 of
AI & Data Science Foundations. Uses its unchanged 24-day fictional CSV.
Save this file beside Chapter_18_Bike_Hire_Data.csv (also in this download).
Python standard library only. Train on 16 days, test on 8 new days.
"""
import csv
from pathlib import Path

csv_file = Path(__file__).with_name('Chapter_18_Bike_Hire_Data.csv')
with csv_file.open(newline='', encoding='utf-8') as file:
    rows = [{"day": int(r['day']), "temp": float(r['temperature_c']), "rain": r['rain'], "hires": int(r['hires'])} for r in csv.DictReader(file)]
assert len(rows) == 24, 'Expected 24 fictional observations'
train, test = rows[:16], rows[16:]
mean_x = sum(r['temp'] for r in train) / len(train)
mean_y = sum(r['hires'] for r in train) / len(train)
slope = sum((r['temp']-mean_x)*(r['hires']-mean_y) for r in train) / sum((r['temp']-mean_x)**2 for r in train)
intercept = mean_y-slope*mean_x
baseline = round(mean_y)

def prediction(temp):
    return max(0, round(slope*temp+intercept))

def mae(predictor):
    return sum(abs(r['hires']-predictor(r['temp'])) for r in test)/len(test)

print('TRAIN: 16 days | TEST: 8 unseen days')
print(f'Model: {slope:.2f} * temp + {intercept:.2f}')
print(f'Model MAE: {mae(prediction):.2f} hires')
print(f'Baseline: {baseline} hires; MAE: {mae(lambda _:baseline):.2f} hires')
for r in test:
    print(f"Day {r['day']:2d}: observed {r['hires']:3d}, predicted {prediction(r['temp']):3d}, rain {r['rain']}")
print('Discuss: Is temperature sufficient? How might rain affect predictions?')
