"""Known-case tests for point-in-time filtering (StockLab overhaul, Part 19)."""
from __future__ import annotations

from datetime import date

from app.engines.metrics.point_in_time import as_of_snapshot
from app.engines.types import LineItems


def _li(period_end, filing_date=None, **kwargs):
    return LineItems(
        security_id="TEST", period_end=date.fromisoformat(period_end),
        period_type="FY", filing_date=date.fromisoformat(filing_date) if filing_date else None,
        currency="USD", **kwargs,
    )


def test_excludes_periods_filed_after_as_of_date():
    periods = [
        _li("2025-12-31", filing_date="2026-02-15", revenue=1000),  # filed AFTER the as-of date below
        _li("2024-12-31", filing_date="2025-02-10", revenue=900),
    ]
    result = as_of_snapshot(periods, as_of=date(2026, 1, 1))
    assert len(result.periods) == 1
    assert result.periods[0].revenue == 900
    assert result.excluded_count == 1


def test_includes_period_filed_exactly_on_as_of_date():
    periods = [_li("2025-12-31", filing_date="2026-01-01", revenue=1000)]
    result = as_of_snapshot(periods, as_of=date(2026, 1, 1))
    assert len(result.periods) == 1


def test_falls_back_to_period_end_when_filing_date_missing_and_counts_it():
    periods = [_li("2025-12-31", filing_date=None, revenue=1000)]
    result = as_of_snapshot(periods, as_of=date(2026, 6, 1))
    assert len(result.periods) == 1
    assert result.used_period_end_fallback_count == 1


def test_excluded_period_with_missing_filing_date_not_counted_toward_fallback():
    periods = [_li("2026-06-30", filing_date=None, revenue=1000)]  # period_end after as_of
    result = as_of_snapshot(periods, as_of=date(2026, 1, 1))
    assert result.periods == []
    assert result.excluded_count == 1
    assert result.used_period_end_fallback_count == 0


def test_preserves_most_recent_first_order_among_kept_periods():
    periods = [
        _li("2025-12-31", filing_date="2026-02-01", revenue=1000),
        _li("2024-12-31", filing_date="2025-02-01", revenue=900),
        _li("2023-12-31", filing_date="2024-02-01", revenue=800),
    ]
    result = as_of_snapshot(periods, as_of=date(2025, 6, 1))
    assert [p.revenue for p in result.periods] == [900, 800]


ALL_TESTS = [obj for name, obj in list(globals().items()) if name.startswith("test_") and callable(obj)]

if __name__ == "__main__":
    passed, failed = 0, []
    for fn in ALL_TESTS:
        try:
            fn()
            passed += 1
            print(f"PASS  {fn.__name__}")
        except AssertionError as e:
            failed.append(fn.__name__)
            print(f"FAIL  {fn.__name__}: {e}")
    print(f"\n{passed}/{len(ALL_TESTS)} passed")
    if failed:
        raise SystemExit(1)
