"""One reusable reader for student-owned comma- or tab-delimited text files."""
from pathlib import Path
import csv
import pandas as pd


def read_data(filename, delimiter=None):
    """Return a pandas DataFrame (a table with named columns).

    delimiter=None detects comma versus tab; use ',' or '\t' to override.
    The first line must contain column headings. Blank cells, NA and NaN are
    missing values. We retain original column names, including spaces.
    """
    path = Path(filename)
    if not path.is_file():
        raise FileNotFoundError(f"Cannot find {path}. Edit DATA_FILE at the top of the script.")
    if path.suffix.lower() in {'.rds', '.rdata'}:
        raise ValueError('Please use a CSV or tab-delimited text file, not an R dataset.')
    with path.open(encoding='utf-8-sig', newline='') as file:
        sample = file.read(65536)
    if not sample.strip():
        raise ValueError('The input file is empty.')
    if delimiter is None:
        try:
            delimiter = csv.Sniffer().sniff(sample, delimiters=',\t').delimiter
        except csv.Error:
            # Allows a one-column dataset when there is nothing to detect.
            delimiter = '\t' if '\t' in sample.splitlines()[0] else ','
    if delimiter not in {',', '\t'}:
        raise ValueError("DELIMITER must be None, ',' or '\\t'.")
    headings = next(csv.reader(sample.splitlines(), delimiter=delimiter))
    headings = [name.strip() for name in headings]
    if any(not name for name in headings) or len(set(headings)) != len(headings):
        raise ValueError('Each column needs a nonblank, unique heading.')
    data = pd.read_csv(path, sep=delimiter, encoding='utf-8-sig',
                       keep_default_na=False, na_values=['', 'NA', 'NaN', 'nan', 'N/A'],
                       skipinitialspace=True)
    data.columns = headings
    for name in data.select_dtypes(include=['object', 'string']):
        data[name] = data[name].str.strip().replace('', pd.NA)
    if data.empty:
        raise ValueError('The file has headings but no observations.')
    return data


def binary_response(values, positive_class=1):
    """Map a two-category Y to 0/1; leave missing Y missing.

    yes/true/1 and no/false/0 (including telecom's trailing periods) work
    automatically. For other labels, set POSITIVE_CLASS, e.g. 'purchased'.
    """
    def normalize(value):
        if pd.isna(value):
            return None
        text = str(value).strip().lower().rstrip('.')
        if text in {'true', 'yes', '1', '1.0'}:
            return '1'
        if text in {'false', 'no', '0', '0.0'}:
            return '0'
        return text
    normalized = values.map(normalize)
    levels = list(normalized.dropna().unique())
    positive = normalize(positive_class)
    if len(levels) != 2 or positive not in levels:
        raise ValueError(f'Y must have two observed classes. Found {levels}; '
                         f'POSITIVE_CLASS={positive_class!r}.')
    return normalized.map(lambda v: float(v == positive) if v is not None else float('nan'))
