# Tactiverge Academy — companion code for "Reading files and CSV data"
# Lesson: https://tactiverge.win/academy/computational-engineering/python-fundamentals/files-and-csv-data/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
lines = ["time_s,temp_c", "0,21.4", "10,21.9", "20,22.7", "30,23.1"]

with open("temps.csv", "w", encoding="utf-8") as f:
    for line in lines:
        f.write(line + "\n")

print("Saved temps.csv")


# ── Example 2 ────────────────────────────────────────
with open("temps.csv", encoding="utf-8") as f:
    for line in f:
        print(repr(line))


# ── Example 3 ────────────────────────────────────────
times = []
temps = []

with open("temps.csv", encoding="utf-8") as f:
    header = f.readline()          # read and skip the first line
    for line in f:
        t_text, temp_text = line.strip().split(",")
        times.append(float(t_text))
        temps.append(float(temp_text))

print(times)
print(temps)
rate = (temps[-1] - temps[0]) / (times[-1] - times[0])   # °C per second
print(f"Warming at {rate * 60:.2f} °C per minute")


# ── Example 4 ────────────────────────────────────────
import csv

rows = [
    ["time_s", "current_a", "rpm", "note"],
    [0.0, 0.42, 0, "start"],
    [0.5, 1.85, 140, ""],
    [1.0, 1.10, 210, ""],
    [1.5, "", 212, "current sensor dropout"],
    [2.0, 1.04, 215, "load added, then removed"],
]

with open("drive_log.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows(rows)

with open("drive_log.csv", encoding="utf-8") as f:
    print(f.read())


# ── Example 5 ────────────────────────────────────────
import csv

currents = []
missing = 0

with open("drive_log.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        if row["current_a"] == "":
            missing += 1
            continue                  # skip to the next row
        currents.append(float(row["current_a"]))

print(f"{len(currents)} current readings, {missing} missing")
print(f"Peak current: {max(currents):.2f} A")
print(f"Mean current: {sum(currents) / len(currents):.3f} A")


# ── Example 6 ────────────────────────────────────────
import csv

with open("drive_log.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

summary = []
for column in ["current_a", "rpm"]:
    values = [float(r[column]) for r in rows if r[column] != ""]
    summary.append([column, len(values), min(values), max(values)])

with open("drive_summary.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["column", "count", "min", "max"])
    writer.writerows(summary)

with open("drive_summary.csv", encoding="utf-8") as f:
    print(f.read(), end="")
