# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import random
import pytest

from asv.step_detect import (solve_potts, solve_potts_autogamma, solve_potts_approx,
                             detect_regressions, golden_search, median, rolling_median_dev,
                             L1Dist, detect_steps)
from asv import step_detect


try:
    import numpy as np
    HAVE_NUMPY = True
except ImportError:
    HAVE_NUMPY = False

try:
    from asv import _rangemedian
    HAVE_RANGEMEDIAN = True
except ImportError:
    HAVE_RANGEMEDIAN = False


@pytest.fixture(params=[
    "python",
    pytest.mark.skipif(not HAVE_RANGEMEDIAN, reason="compiled asv._rangemedian required")("rangemedian")
])
def use_rangemedian(request):
    if request.param == "rangemedian":
        assert isinstance(step_detect.get_mu_dist([0], p=1), _rangemedian.RangeMedian)
        return True
    else:
        step_detect._rangemedian = None

        def restore():
            if HAVE_RANGEMEDIAN:
                step_detect._rangemedian = _rangemedian
        request.addfinalizer(restore)

        assert isinstance(step_detect.get_mu_dist([0], p=1), L1Dist)
        return False


@pytest.mark.skipif(not HAVE_NUMPY, reason="test needs numpy")
def test_solve_potts(use_rangemedian):
    try:
        np.random.seed(1234)
    except NameError:
        # work around a bug in old pypy/pytest
        pytest.skip("test needs numpy")
        return

    # Easy case, exact solver
    y = [1, 1, 1, 2, 2, 2, 3, 3, 3]