"""Week 1: records, leakage-safe classification, and a scalar gradient update.
Install numpy and scikit-learn in your exercise environment before lesson 2.
"""
import argparse
import math


def lesson1():
    examples = {'labeled spam examples': 'supervised',
                'unlabeled customer similarities': 'unsupervised',
                'action outcomes and points': 'reinforcement'}
    assert len(set(examples.values())) == 3
    print('Lesson 1: the academy contains the conceptual application and reviews.')


def lesson2():
    import numpy as np
    from sklearn.datasets import make_classification
    from sklearn.model_selection import train_test_split
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    from sklearn.linear_model import LogisticRegression
    from sklearn.dummy import DummyClassifier
    from sklearn.metrics import confusion_matrix, accuracy_score

    customers = np.array(['A', 'A', 'B', 'B', 'C', 'C'])
    train, validation, test = customers[:2], customers[2:4], customers[4:]
    assert not set(train) & set(validation)
    assert not set(train) & set(test)
    assert not set(validation) & set(test)
    available_at = {'amount': 0, 'card_age': 0, 'later_refund': 7}
    def validate_features(names, prediction_time=0):
        if any(available_at[name] > prediction_time for name in names):
            raise ValueError('Feature was unavailable at prediction time')
    validate_features(['amount', 'card_age'])
    try:
        validate_features(['amount', 'later_refund'])
    except ValueError:
        pass
    else:
        raise AssertionError('Unavailable future feature was accepted')
    scaler = StandardScaler().fit([[10.0], [20.0]])
    assert np.allclose(scaler.mean_, [15.0])
    assert np.allclose(scaler.transform([[30.0]]), [[3.0]])
    X, y = make_classification(n_samples=240, n_features=6,
                              n_informative=4, n_redundant=0, random_state=42)
    # Independent generated rows permit a row split for this particular task.
    X_dev, X_test, y_dev, y_test = train_test_split(
        X, y, test_size=0.2, stratify=y, random_state=42)
    X_train, X_val, y_train, y_val = train_test_split(
        X_dev, y_dev, test_size=0.25, stratify=y_dev, random_state=42)
    model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
    model.fit(X_train, y_train)
    baseline = DummyClassifier(strategy='most_frequent').fit(X_train, y_train)
    assert model[-2].n_samples_seen_ == len(X_train)
    print('Group intersections: empty. Future refund input rejected. Saved scaler maps 30 to 3.')
    print('Partition sizes:', len(X_train), len(X_val), len(X_test))
    print('Validation accuracy:', accuracy_score(y_val, model.predict(X_val)))
    print('Fixed-model test accuracy:', accuracy_score(y_test, model.predict(X_test)))
    print('Majority baseline test accuracy:', accuracy_score(y_test, baseline.predict(X_test)))
    print('Confusion matrix, true rows / predicted columns, labels [0,1]:')
    print(confusion_matrix(y_test, model.predict(X_test), labels=[0, 1]))
    print('PASS: split and preparation checks; accuracy is measured, not promised.')


def lesson3():
    x, target, weight = 2.0, 6.0, 1.0
    prediction = weight * x
    loss = (prediction - target) ** 2 / 2
    gradient = (prediction - target) * x
    updated = weight - 0.1 * gradient
    new_loss = (updated * x - target) ** 2 / 2
    observed = [prediction, loss, gradient, updated, new_loss]
    expected = [2, 8, -8, 1.8, 2.88]
    assert all(math.isclose(a, b, rel_tol=1e-9) for a, b in zip(observed, expected))
    print('Prediction, loss, gradient, new weight, new loss:', observed)
    for rate in [0.01, 0.1, 1.0]:
        weight = 1.0
        losses = []
        for _ in range(10):
            gradient = (weight * x - target) * x
            weight -= rate * gradient
            losses.append((weight * x - target) ** 2 / 2)
        print('Rate', rate, 'losses:', [round(value, 6) for value in losses])
    assert math.isclose((1.08 * 2 - 6) ** 2 / 2, 7.3728)
    assert math.isclose((9 * 2 - 6) ** 2 / 2, 72)
    print('PASS: all hand-checkable first-step values match.')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--lesson', choices=['1', '2', '3', 'all'], default='all')
    args = parser.parse_args()
    for number, function in [('1', lesson1), ('2', lesson2), ('3', lesson3)]:
        if args.lesson in (number, 'all'):
            function()
