"""Tests for GLB beta computation."""
import pytest
import pandas as pd
import numpy as np

from qmoms import compute_glb_betas


class TestComputeGLBBetas:

    @pytest.fixture(scope="class")
    def beta_df(self, raw_data):
        _, _, df_return = raw_data
        return compute_glb_betas(df_return, parallel=False)

    def test_output_shape(self, beta_df):
        assert beta_df.shape == (1875, 11)

    def test_output_columns(self, beta_df):
        expected = ['id', 'date', 'Bmj', 'Bm2j', 'Bj2j', 'Bmjj',
                    'Bm3j', 'Bj3j', 'Bm2jj', 'Bmj2j', 'Bcapm']
        assert list(beta_df.columns) == expected

    def test_ids_present(self, beta_df):
        ids = beta_df['id'].unique()
        assert set(ids) == {'12490', '14541', '14593', '18542', '93436'}

    def test_bcapm_positive(self, beta_df):
        assert (beta_df['Bcapm'] > 0).all()

    def test_bmj_range(self, beta_df):
        assert beta_df['Bmj'].min() > 0
        assert beta_df['Bmj'].max() < 1

    def test_dates_are_timestamps(self, beta_df):
        assert pd.api.types.is_datetime64_any_dtype(beta_df['date'])

    def test_mean_bcapm(self, beta_df):
        assert abs(beta_df['Bcapm'].mean() - 1.023827) < 0.01

    def test_first_row_values(self, beta_df):
        row = beta_df.iloc[0]
        assert row['id'] == '12490'
        assert abs(row['Bmj'] - 0.489644) < 0.001
        assert abs(row['Bcapm'] - 0.417782) < 0.001

    def test_empty_input(self):
        empty_df = pd.DataFrame(columns=['mktrf', 'rf', 'asset1'])
        empty_df.index = pd.DatetimeIndex([], name='date')
        result = compute_glb_betas(empty_df, ids=['asset1'])
        assert result.shape[0] == 0
