import pandas as pd

import tools.run_treasury_curve_event_study as study


def _btc_and_yields():
    dates = pd.date_range("2024-01-01", periods=8, freq="D")
    btc = pd.DataFrame({"time": dates, "close": range(100, 108)})
    yields = pd.DataFrame({"time": dates, "DGS2": [5.0, 4.9, 4.8, 4.7, 4.6, 4.5, 4.4, 4.3],
                           "DGS10": [4.9, 4.8, 4.7, 4.6, 4.5, 4.4, 4.3, 4.2],
                           "DGS30": [4.8, 4.7, 4.6, 4.5, 4.4, 4.3, 4.2, 4.1]})
    return btc, yields


def test_alignment_lags_yields_by_one_btc_day():
    btc, yields = _btc_and_yields()

    aligned = study.align_point_in_time(btc, yields)

    assert aligned["time"].tolist() == btc["time"].iloc[1:].tolist()
    assert aligned["DGS10"].tolist() == yields["DGS10"].iloc[:-1].tolist()


def test_load_yields_accepts_fred_observation_date(tmp_path):
    source = tmp_path / "fred.csv"
    source.write_text("observation_date,DGS2,DGS10,DGS30\n2024-01-01,4.1,4.0,3.9\n")

    loaded = study.load_yields(source)

    assert loaded.columns.tolist() == ["time", "DGS2", "DGS10", "DGS30"]


def test_hypotheses_identify_curve_inversion_and_joint_sharp_drop():
    btc, yields = _btc_and_yields()
    frame = study.build_signals(study.align_point_in_time(btc, yields), change_days=2, sharp_drop_bps=15)

    assert frame["ten_above_thirty"].all()
    assert not frame["all_yields_sharply_falling"].iloc[:2].any()
    assert not frame["two_year_sharply_falling"].iloc[:2].any()
    assert frame["two_year_sharply_falling"].iloc[2:].all()
    assert frame["all_yields_sharply_falling"].iloc[2:].all()


def test_study_reports_independent_baseline_and_signal_samples():
    btc, yields = _btc_and_yields()

    report = study.study(btc, yields, change_days=2, sharp_drop_bps=15)

    full = report["windows"]["full"]
    assert full["baseline"]["horizons"]["1"]["n"] == 6
    assert full["ten_above_thirty"]["signal_days"] == 7
    assert full["two_year_sharply_falling"]["signal_days"] == 5
    assert full["all_yields_sharply_falling"]["signal_days"] == 5
