"""第 09 章 路徑與檔案讀寫。"""

# read-write-text
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    report = Path(folder) / "report.txt"
    report.write_text("資料已核對\n共 3 筆\n", encoding="utf-8")
    lines = report.read_text(encoding="utf-8").splitlines()
    print(lines[0])
    print("行數", len(lines))

# read-csv
import csv
from pathlib import Path
from tempfile import TemporaryDirectory


def total_minutes(path):
    with path.open(encoding="utf-8-sig", newline="") as handle:
        rows = csv.DictReader(handle)
        if sorted(rows.fieldnames or []) != ["minutes", "task"]:
            raise ValueError("CSV 必須包含 task 與 minutes")
        return sum(int(row["minutes"]) for row in rows)


with TemporaryDirectory() as folder:
    path = Path(folder) / "work-log.csv"
    path.write_text("task,minutes\n整理,15\n核對,25\n", encoding="utf-8")
    print("合計", total_minutes(path))
    path.write_text("task,minutes\n", encoding="utf-8")
    print("只有表頭", total_minutes(path))
    path.write_text("task,hours\n整理,1\n", encoding="utf-8")
    try:
        total_minutes(path)
    except ValueError as error:
        print(error)

# roundtrip-json
import json
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    settings_path = Path(folder) / "settings.json"
    with settings_path.open("w", encoding="utf-8") as handle:
        json.dump({"工作類型": "校對", "提醒分鐘": 20}, handle, ensure_ascii=False)
    with settings_path.open(encoding="utf-8") as handle:
        settings = json.load(handle)

print(settings["工作類型"], settings["提醒分鐘"])

# files-practice
note_lines = ["開始核對", "已全部核對"]
empty_csv = "task,minutes\n"
# 用 TemporaryDirectory 建立練習檔，再呼叫 total_minutes()。
print("確認文字、空表格與缺檔的結果。")

# files-solutions
with TemporaryDirectory() as folder:
    directory = Path(folder)
    notes = directory / "notes.txt"
    notes.write_text("開始核對\n已全部核對\n", encoding="utf-8")
    print(notes.read_text(encoding="utf-8").splitlines()[1])

    work_log = directory / "empty.csv"
    work_log.write_text("task,minutes\n", encoding="utf-8")
    print(total_minutes(work_log))
    try:
        total_minutes(directory / "missing.csv")
    except FileNotFoundError:
        print("找不到紀錄檔")
