"""Shared housekeeping. The eleven lesson scripts contain the model workflows.

Keep this file and input_data.py beside those scripts; no package setup needed.
"""
from pathlib import Path
import warnings
import numpy as np
import pandas as pd
import scipy.stats as st
import statsmodels.api as sm
from statsmodels.tools.sm_exceptions import PerfectSeparationWarning
from sklearn.metrics import (mean_absolute_error, mean_squared_error, r2_score,
                             confusion_matrix, accuracy_score, roc_auc_score, roc_curve)
import matplotlib
matplotlib.use('Agg')  # Save figures; also works on servers without a display.
import matplotlib.pyplot as plt
from input_data import read_data, binary_response


def output_folder(script_file):
    folder = Path(script_file).resolve().parent / 'outputs' / Path(script_file).stem
    folder.mkdir(parents=True, exist_ok=True)
    # Remove only known generated artifacts, so changing a holdout/refit setting
    # cannot leave a previous run's confusion matrix or coefficient table behind.
    generated = ['model_summary.txt', 'coefficients.csv', 'predictions.csv',
                 'metrics.csv', 'actual_vs_predicted.png', 'residuals.png',
                 'selection_history.csv', 'all_models.csv', 'top_models_by_size.csv',
                 'criterion_winners.csv', 'odds_ratios.csv', 'pseudo_r_squared.txt',
                 'training_confusion_matrix.csv', 'holdout_confusion_matrix.csv',
                 'roc_curve.png', 'cross_validation.csv', 'lasso_coefficients.csv',
                 'lambda_choices.csv', 'lasso_paths_and_cv.png', 'tree_rules.txt',
                 'feature_importance.csv', 'decision_tree.png']
    for name in generated:
        (folder / name).unlink(missing_ok=True)
    return folder


def prepare(filename, delimiter, target, predictors, categorical=(),
            sort_by=None, holdout_count=0, test_fraction=0, seed=9,
            classification=False, positive_class=1):
    """Read data, choose training rows FIRST, and encode predictors.

    Missing predictors exclude a row from training/prediction; missing Y only
    excludes it from training. Such rows can still receive forecasts.
    Numeric category codes (e.g., Area Code) belong in CATEGORICAL_COLUMNS.
    """
    data = read_data(filename, delimiter)
    names = [target] + list(predictors) + list(categorical) + ([sort_by] if sort_by else [])
    missing = sorted(set(names) - set(data.columns))
    if missing:
        raise ValueError(f'Unknown columns: {missing}. Available: {list(data.columns)}')
    if target in predictors or len(set(predictors)) != len(predictors):
        raise ValueError('Predictor names must be unique and must exclude Y.')
    if not set(categorical).issubset(predictors):
        raise ValueError('CATEGORICAL_COLUMNS must be a subset of X_COLUMNS.')
    if holdout_count < 0 or int(holdout_count) != holdout_count:
        raise ValueError('HOLDOUT_COUNT must be a nonnegative integer.')
    if not 0 <= test_fraction < 1 or (holdout_count and test_fraction):
        raise ValueError('Use one holdout scheme: a count OR a fraction between 0 and 1.')
    data.insert(0, '_source_row', np.arange(1, len(data) + 1))
    if sort_by:
        if data[sort_by].isna().any():
            raise ValueError('The sort column contains missing values.')
        data = data.sort_values(sort_by, kind='stable').reset_index(drop=True)
    if classification:
        y = binary_response(data[target], positive_class)
    else:
        y = pd.to_numeric(data[target], errors='raise').astype(float)
    y = y.replace([np.inf, -np.inf], np.nan)
    raw = data[list(predictors)].copy()
    cat = [name for name in predictors if name in categorical or
           not pd.api.types.is_numeric_dtype(raw[name])]
    for name in predictors:
        if name not in cat:
            raw[name] = pd.to_numeric(raw[name], errors='raise').astype(float)
    raw = raw.replace([np.inf, -np.inf], np.nan)
    reserved = pd.Series(False, index=data.index)
    observed = data.index[y.notna()]
    if holdout_count:
        if holdout_count >= len(observed):
            raise ValueError('Holdouts would leave no observed training rows.')
        reserved.loc[observed[-holdout_count:]] = True
    complete_x = raw.notna().all(axis=1)
    candidates = data.index[y.notna() & complete_x & ~reserved]
    if test_fraction:
        from sklearn.model_selection import train_test_split
        _, test = train_test_split(candidates, test_size=test_fraction, random_state=seed,
                                   stratify=y.loc[candidates] if classification else None)
        reserved.loc[test] = True
    train = complete_x & y.notna() & ~reserved
    if train.sum() < 3:
        raise ValueError('Fewer than three complete training observations.')
    if classification and y[train].nunique() != 2:
        raise ValueError('The training set needs both response classes.')
    # Learn category levels from TRAINING only; future unseen levels cannot be scored.
    X = pd.DataFrame(index=data.index)
    groups = {}
    for i, name in enumerate(predictors):
        key = f'x{i}: {name}'  # Prefix prevents collisions; name stays readable in output.
        if name in cat:
            levels = sorted(raw.loc[train, name].astype(str).unique())
            unseen = raw[name].notna() & ~raw[name].astype(str).isin(levels)
            if unseen.any():
                print(f'{name}: {unseen.sum()} rows have unseen categories; predictions omitted.')
                complete_x &= ~unseen
            columns = []
            for j, level in enumerate(levels[1:], start=1):
                column = f'{key} = {level}'
                X[column] = (raw[name].astype(str) == level).astype(float)
                columns.append(column)
            groups[name] = columns
            print(f'{name}: reference category = {levels[0]!r}; comparisons = {levels[1:]}')
        else:
            X[key] = raw[name]
            groups[name] = [key]
    usable = {name: cols for name, cols in groups.items()
              if cols and any(X.loc[train, col].nunique() > 1 for col in cols)}
    for name in set(groups) - set(usable):
        print(f'Excluded constant predictor: {name}')
    groups = usable
    X = X[[col for cols in groups.values() for col in cols]]
    status = pd.Series('excluded_missing_predictor', index=data.index)
    status.loc[complete_x & y.isna()] = 'forecast'
    status.loc[complete_x & y.notna() & reserved] = 'holdout'
    status.loc[train] = 'training'
    print(f'Training: {train.sum()}; holdout: {(status == "holdout").sum()}; '
          f'forecast: {(status == "forecast").sum()}; excluded: {(~complete_x).sum()}')
    return data, y, X, groups, train, complete_x, status


def design(X, groups, selected):
    """An intercept plus columns for the selected ORIGINAL variables."""
    columns = [col for name in selected for col in groups[name]]
    out = X[columns].copy()
    out.insert(0, 'Intercept', 1.0)
    return out.astype(float)


def fit_model(y, X, groups, selected, train, logistic=False):
    matrix = design(X, groups, selected).loc[train]
    if np.linalg.matrix_rank(matrix.to_numpy()) < matrix.shape[1]:
        raise ValueError(f'Rank-deficient model: {selected}. Remove redundant predictors.')
    if len(matrix) <= matrix.shape[1]:
        raise ValueError('Too few training rows for this many model coefficients.')
    if logistic:
        with warnings.catch_warnings():
            warnings.simplefilter('error', PerfectSeparationWarning)
            try:
                model = sm.GLM(y.loc[train], matrix, family=sm.families.Binomial()).fit()
            except PerfectSeparationWarning as error:
                raise ValueError('Perfect separation: unpenalized logistic estimates are not finite.') from error
        if not model.converged or not np.isfinite(model.params).all():
            raise ValueError('Logistic model did not converge. Try fewer predictors.')
        return model
    return sm.OLS(y.loc[train], matrix).fit()


def stepwise(y, X, groups, train, sle, sls, logistic=False, max_steps=100):
    """Bidirectional selection: partial F tests for OLS, LR tests for logistic.

    All dummy columns for a categorical variable enter/leave together.
    The original Shiny SLE > SLS defaults can cause an add/remove cycle.
    Stop at the repeated state and explain it rather than loop forever.
    """
    if not 0 < sle <= 1 or not 0 < sls <= 1:
        raise ValueError('SLE and SLS must be in (0, 1].')
    selected, history, seen = [], [], {()}
    current = fit_model(y, X, groups, selected, train, logistic)

    def p_test(full, reduced):
        if logistic:
            df = full.df_model - reduced.df_model
            return st.chi2.sf(max(0, 2 * (full.llf - reduced.llf)), df) if df > 0 else np.nan
        return full.compare_f_test(reduced)[1]

    def record(action, name, p):
        history.append({'step': len(history)+1, 'action': action,
                        'variable': name, 'p_value': p,
                        'selected': ' + '.join(selected) or '(intercept only)'})

    for _ in range(max_steps):
        changed = False
        choices = []
        for name in groups:
            if name not in selected:
                try:
                    candidate = fit_model(y, X, groups, selected+[name], train, logistic)
                    p = p_test(candidate, current)
                    if np.isfinite(p):
                        choices.append((p, name, candidate))
                except ValueError as error:
                    print(f'Skipping entry candidate {name}: {error}')
        if choices:
            p, name, candidate = min(choices, key=lambda item: item[0])
            if p < sle:
                selected.append(name)
                current = candidate
                record('enter', name, p)
                changed = True
        # Re-check every selected term after each addition.
        while selected:
            choices = []
            for name in selected:
                reduced_names = [item for item in selected if item != name]
                reduced = fit_model(y, X, groups, reduced_names, train, logistic)
                p = p_test(current, reduced)
                if np.isfinite(p):
                    choices.append((p, name, reduced))
            if not choices:
                break
            p, name, reduced = max(choices, key=lambda item: item[0])
            if p <= sls:
                break
            selected.remove(name)
            current = reduced
            record('remove', name, p)
            changed = True
        if not changed:
            break
        state = tuple(sorted(selected))
        if state in seen:
            print('Stepwise stopped at a repeated model. SLE > SLS can cause cycling; '
                  'try SLE=0.05 and SLS=0.10 for a conventional ordering.')
            record('stop_cycle', '', np.nan)
            break
        seen.add(state)
    else:
        raise RuntimeError('Stepwise reached MAX_STEPS. Review thresholds and candidates.')
    return selected, current, pd.DataFrame(history, columns=['step','action','variable','p_value','selected'])


def write_summary(model, folder, groups):
    text = model.summary().as_text() + '\n\nOriginal variable to encoded columns:\n' + repr(groups)
    print(text)
    (folder / 'model_summary.txt').write_text(text, encoding='utf-8')
    interval = model.conf_int()
    table = pd.DataFrame({'coefficient': model.params, 'std_error': model.bse,
                          'p_value': model.pvalues, 'lower_95': interval[0], 'upper_95': interval[1]})
    table.to_csv(folder / 'coefficients.csv', index_label='term')


def regression_report(data, y, predicted, status, folder):
    """Report training and holdout separately; retain every original row."""
    report = data.copy()
    report['sample'] = status
    report['actual_y'] = y
    report['predicted_y'] = predicted
    report['residual'] = y - predicted
    report.to_csv(folder / 'predictions.csv', index=False)
    metrics = []
    for sample in ['training', 'holdout']:
        mask = (status == sample) & y.notna() & predicted.notna()
        if mask.any():
            actual, pred = y[mask], predicted[mask]
            nonzero = actual != 0
            metrics.append({'sample': sample, 'n': int(mask.sum()),
                            'MAE': mean_absolute_error(actual, pred),
                            'RMSE': np.sqrt(mean_squared_error(actual, pred)),
                            'R_squared': r2_score(actual, pred) if len(actual)>1 else np.nan,
                            'MAPE_percent': (100*np.mean(np.abs((actual[nonzero]-pred[nonzero])/actual[nonzero]))) if nonzero.any() else np.nan})
    table = pd.DataFrame(metrics)
    print(table.to_string(index=False))
    table.to_csv(folder / 'metrics.csv', index=False)
    plt.figure(figsize=(10, 5))
    plt.plot(np.arange(1, len(data)+1), y, 'o-', label='Actual')
    plt.plot(np.arange(1, len(data)+1), predicted, '.--', label='Predicted (including forecasts)')
    plt.xlabel('Observation position in chosen sort order'); plt.ylabel('Y'); plt.legend()
    plt.tight_layout(); plt.savefig(folder / 'actual_vs_predicted.png'); plt.close()
    plt.figure(figsize=(7, 5))
    mask = (status == 'training') & predicted.notna()
    plt.scatter(predicted[mask], (y-predicted)[mask]); plt.axhline(0, color='black')
    plt.xlabel('Training fitted value'); plt.ylabel('Residual')
    plt.tight_layout(); plt.savefig(folder / 'residuals.png'); plt.close()
    print(f'Results saved in {folder}')


def classification_report(data, y, probability, status, cutoff, folder):
    if not 0 <= cutoff <= 1:
        raise ValueError('PROBABILITY_CUTOFF must be between 0 and 1.')
    predicted = pd.Series(np.nan, index=data.index)
    valid = probability.notna()
    predicted[valid] = (probability[valid] >= cutoff).astype(int)
    report = data.copy()
    report['sample'] = status; report['actual_01'] = y
    report['probability_positive'] = probability; report['predicted_01'] = predicted
    report.to_csv(folder / 'predictions.csv', index=False)
    metrics = []
    plt.figure(figsize=(6, 5))
    for sample in ['training', 'holdout']:
        mask = (status == sample) & y.notna() & valid
        if not mask.any():
            continue
        actual, pred, prob = y[mask], predicted[mask], probability[mask]
        cm = confusion_matrix(actual, pred, labels=[0,1])
        tn, fp, fn, tp = cm.ravel()
        pd.DataFrame(cm, index=['actual_0','actual_1'], columns=['predicted_0','predicted_1']).to_csv(folder / f'{sample}_confusion_matrix.csv')
        print(f'{sample} confusion matrix (rows=actual 0,1; columns=predicted 0,1):\n{cm}')
        auc = roc_auc_score(actual, prob) if actual.nunique()==2 else np.nan
        metrics.append({'sample':sample, 'n':len(actual), 'accuracy':accuracy_score(actual,pred),
                        'sensitivity_recall':tp/(tp+fn) if tp+fn else np.nan,
                        'specificity':tn/(tn+fp) if tn+fp else np.nan,
                        'precision':tp/(tp+fp) if tp+fp else np.nan, 'ROC_AUC':auc})
        if actual.nunique()==2:
            fpr, tpr, _ = roc_curve(actual, prob)
            plt.plot(fpr,tpr,label=f'{sample} AUC={auc:.3f}')
    plt.plot([0,1],[0,1],'k--'); plt.xlabel('False positive rate'); plt.ylabel('True positive rate')
    plt.legend(); plt.tight_layout(); plt.savefig(folder/'roc_curve.png'); plt.close()
    table = pd.DataFrame(metrics); print(table.to_string(index=False))
    table.to_csv(folder / 'metrics.csv', index=False)
    print(f'Results saved in {folder}')
