#!/usr/bin/env python3
"""Original course teaching example. SPDX-License-Identifier: MIT."""
import csv
import json
import math
from pathlib import Path


def read_csv(path, required):
    with Path(path).open(encoding="utf-8-sig", newline="") as stream:
        reader = csv.DictReader(stream)
        fields = reader.fieldnames or []
        if len(set(fields)) != len(fields):
            raise ValueError("CSV has duplicate column names")
        if not set(required).issubset(fields):
            raise ValueError("CSV needs columns: " + ",".join(required))
        rows = list(reader)
    if not rows:
        raise ValueError("CSV contains no data rows; fill in the template first")
    if any(None in row for row in rows):
        raise ValueError("CSV has a row with more values than column names")
    return rows


def number(value, name):
    try:
        result = float(value)
    except (TypeError, ValueError) as exc:
        raise ValueError(f"{name} must be a finite number") from exc
    if not math.isfinite(result):
        raise ValueError(f"{name} must be a finite number")
    return result


def flag(value, name):
    values = {"0": False, "false": False, "1": True, "true": True}
    key = str(value).strip().lower()
    if key not in values:
        raise ValueError(f"{name} must be 0/1 or false/true")
    return values[key]


def output_dir(path):
    """Refuse overwriting a previous run, including input files."""
    result = Path(path)
    if result.exists() and (not result.is_dir() or any(result.iterdir())):
        raise ValueError(f"Output directory must be new or empty: {result}")
    result.mkdir(parents=True, exist_ok=True)
    return result


def write_json(path, data):
    with Path(path).open("x", encoding="utf-8") as stream:
        json.dump(data, stream, ensure_ascii=False, indent=2, allow_nan=False)
        stream.write("\n")


def write_csv(path, fields, rows):
    with Path(path).open("x", encoding="utf-8", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)
