from __future__ import annotations

import sys
import importlib.util
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2]))

_SCRIPT_PATH = Path(__file__).resolve().parents[2] / "scripts" / "enrich_earnings_history_features.py"
_SPEC = importlib.util.spec_from_file_location("enrich_earnings_history_features", _SCRIPT_PATH)
assert _SPEC and _SPEC.loader
_MODULE = importlib.util.module_from_spec(_SPEC)
_SPEC.loader.exec_module(_MODULE)
compute_history_features = _MODULE.compute_history_features


def test_compute_history_features_builds_prior_vector_and_summary() -> None:
    quarters = [
        {"reported_date": "2026-01-29", "surprise_percentage": 6.25},
        {"reported_date": "2025-10-30", "surprise_percentage": 4.52},
        {"reported_date": "2025-07-31", "surprise_percentage": 9.48},
        {"reported_date": "2025-05-01", "surprise_percentage": 7.0},
        {"reported_date": "2025-01-30", "surprise_percentage": -2.0},
        {"reported_date": "2024-10-31", "surprise_percentage": 3.0},
    ]
    features = compute_history_features("AAPL", "2026-01-29", quarters)
    assert features["sue_lag_1_pct"] == 4.52
    assert features["sue_lag_2_pct"] == 9.48
    assert features["sue_lag_3_pct"] == 7.0
    assert features["sue_lag_4_pct"] == -2.0
    assert features["sue_hist_latest_pct"] == 4.52
    assert features["sue_hist_mean_4q"] == (4.52 + 9.48 + 7.0 - 2.0) / 4
    assert features["sue_hist_pos_rate_4q"] == 0.75
    assert features["sue_hist_streak_pos"] == 3.0


def test_compute_history_features_returns_empty_when_event_not_matched() -> None:
    quarters = [
        {"reported_date": "2026-01-29", "surprise_percentage": 6.25},
        {"reported_date": "2025-10-30", "surprise_percentage": 4.52},
    ]
    features = compute_history_features("AAPL", "2026-02-20", quarters)
    assert all(value is None for value in features.values())
