"""A conventional forest used only to initialize trainable MINT trees."""
from __future__ import annotations

import numpy as np
from sklearn.ensemble import ExtraTreesClassifier


def fit_seed_forest(x, y, n_trees=64, depth=6, min_leaf=8, seed=42, n_jobs=-1):
    x = np.asarray(x, dtype=np.float32)
    y = np.asarray(y, dtype=np.float64)
    if x.ndim != 2 or not len(x) or not np.isfinite(x).all():
        raise ValueError('Seed features must be a nonempty finite matrix.')
    if len(y) != len(x) or not np.isin(y, [0, 1]).all():
        raise ValueError('Seed labels must be binary and match the features.')
    if not 1 <= depth <= 10 or n_trees < 1 or min_leaf < 1:
        raise ValueError('Require depth in 1..10, positive n_trees and min_leaf.')
    seed_model = ExtraTreesClassifier(n_estimators=n_trees, max_depth=depth,
                                     min_samples_leaf=min_leaf, max_features='sqrt',
                                     class_weight='balanced',
                                     bootstrap=False, random_state=seed, n_jobs=n_jobs)
    seed_model.fit(x, y)
    n_nodes, n_leaves = 2 ** depth - 1, 2 ** depth
    feature = np.zeros((n_trees, n_nodes), dtype=np.int64)
    threshold = np.zeros((n_trees, n_nodes), dtype=np.float32)
    leaf_prob = np.empty((n_trees, n_leaves), dtype=np.float32)
    active = np.zeros((n_trees, n_nodes), dtype=bool)
    for t, estimator in enumerate(seed_model.estimators_):
        tree = estimator.tree_
        assignment = estimator.apply(x)
        count = np.bincount(assignment, minlength=tree.node_count)
        positives = np.bincount(assignment, weights=y, minlength=tree.node_count)
        # Natural-prevalence posterior; no class-weighted tree.value or teacher score.
        probability = (positives + .5) / (count + 1.)

        def copy_node(source, dest, level, first_leaf, width):
            if tree.children_left[source] < 0:
                leaf_prob[t, first_leaf:first_leaf + width] = probability[source]
                return
            if level >= depth:
                raise RuntimeError('Initializer exceeds the declared tree depth.')
            feature[t, dest] = tree.feature[source]
            raw_threshold = tree.threshold[source]
            represented = np.float32(raw_threshold)
            # The model inputs are float32, sklearn thresholds float64. Round
            # downward so every representable input retains sklearn's <= / >
            # branch even when the threshold falls between adjacent floats.
            if represented > raw_threshold:
                represented = np.nextafter(represented, np.float32(-np.inf))
            threshold[t, dest] = represented
            active[t, dest] = True
            half = width // 2
            copy_node(tree.children_left[source], 2 * dest + 1, level + 1, first_leaf, half)
            copy_node(tree.children_right[source], 2 * dest + 2, level + 1, first_leaf + half, half)

        copy_node(0, 0, 0, 0, n_leaves)
    return dict(feature_index=feature, thresholds=threshold, leaf_prob=leaf_prob,
                active_nodes=active, n_features=x.shape[1], n_trees=n_trees, depth=depth,
                seed=int(seed), min_leaf=int(min_leaf), smoothing=.5,
                initializer='ExtraTreesClassifier; balanced split discovery; unweighted leaf counts; max_features=sqrt')


def seed_predict(blueprint, x):
    """Predict from converted seed leaves with exact hard axis-aligned routing."""
    x = np.asarray(x, dtype=np.float32)
    trees = np.arange(blueprint['n_trees'])[None, :]
    nodes = np.zeros((len(x), blueprint['n_trees']), dtype=np.int64)
    rows = np.arange(len(x))[:, None]
    for _ in range(blueprint['depth']):
        feature = blueprint['feature_index'][trees, nodes]
        right = x[rows, feature] > blueprint['thresholds'][trees, nodes]
        nodes = 2 * nodes + 1 + right
    leaves = nodes - (2 ** blueprint['depth'] - 1)
    return blueprint['leaf_prob'][trees, leaves].mean(axis=1)
