"""Default-risk model for existing cardholders with six months of history."""
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
from threadpoolctl import threadpool_limits

TARGET = "default payment next month"
CUTOFF = 0.20
_PAY = ["PAY_0", "PAY_2", "PAY_3", "PAY_4", "PAY_5", "PAY_6"]
_BILL = [f"BILL_AMT{i}" for i in range(1, 7)]
_PAID = [f"PAY_AMT{i}" for i in range(1, 7)]
_FEATURES = ["LIMIT_BAL"] + _PAY + _BILL + _PAID


def _features(df):
    if not df.columns.is_unique:
        raise ValueError("Column names must be unique.")
    a = df.loc[:, _FEATURES].to_numpy(dtype=np.float64)
    if not np.isfinite(a).all():
        raise ValueError("Financial inputs must be finite and nonmissing.")
    if (a[:, 0] <= 0).any():
        raise ValueError("LIMIT_BAL must be positive.")

    limit = a[:, :1]
    status, bills, paid = a[:, 1:7], a[:, 7:13], a[:, 13:19]
    extra = np.column_stack([
        (status > 0).sum(axis=1),
        (status >= 2).sum(axis=1),
        status.mean(axis=1),
        status.max(axis=1),
        status[:, :3].mean(axis=1),
        status[:, 0] - status[:, 1],
        bills.mean(axis=1),
        bills.std(axis=1),
        bills[:, 0] - bills[:, -1],
        paid.mean(axis=1),
        paid.std(axis=1),
        (paid == 0).sum(axis=1),
        paid.sum(axis=1) / (np.maximum(bills, 0).sum(axis=1) + 1.0),
    ])
    return np.column_stack([a, bills / limit, paid / limit, extra])


def fit(df):
    """Fit on all supplied rows; ID and demographic columns are ignored."""
    y = pd.to_numeric(df[TARGET], errors="raise")
    if y.isna().any() or set(y.unique()) != {0, 1}:
        raise ValueError("The target must contain both classes, coded 0 and 1.")

    model = make_pipeline(
        FunctionTransformer(_features, validate=False),
        HistGradientBoostingClassifier(
            learning_rate=0.05,
            max_iter=200,
            max_leaf_nodes=7,
            min_samples_leaf=60,
            l2_regularization=10.0,
            early_stopping=False,
            random_state=20261023,
        ),
    )
    with threadpool_limits(limits=1):
        model.fit(df, y.to_numpy(dtype=np.int64))
    return model


def score(model, df):
    """Return P(default=1) in input row order; the target is unnecessary."""
    if len(df) == 0:
        return np.empty(0, dtype=np.float64)
    with threadpool_limits(limits=1):
        return np.asarray(model.predict_proba(df)[:, 1], dtype=np.float64)
