from datetime import date, datetime, timezone

from app.revenue_forecast_service import (
    management_status,
    month_bounds,
    stage_probability,
)


def test_month_bounds_uses_calendar_month_not_rolling_30_days():
    start, end = month_bounds("2026-07")
    assert start == date(2026, 7, 1)
    assert end == date(2026, 7, 31)


def test_month_bounds_defaults_to_reference_month():
    now = datetime(2026, 2, 15, tzinfo=timezone.utc)
    start, end = month_bounds(None, now=now)
    assert start == date(2026, 2, 1)
    assert end == date(2026, 2, 28)


def test_supported_target_with_low_quality_is_not_green():
    result = management_status(target=10_000, forecast_total=10_500, quality_score=0.46)
    assert result["code"] == "supported_low_confidence"
    assert result["tone"] == "orange"


def test_target_below_85_percent_is_not_supported():
    result = management_status(target=10_000, forecast_total=8_000, quality_score=0.90)
    assert result["code"] == "not_supported"
    assert result["tone"] == "red"


def test_target_between_85_and_100_percent_is_at_risk():
    result = management_status(target=10_000, forecast_total=9_000, quality_score=0.90)
    assert result["code"] == "at_risk"


def test_large_history_has_more_influence_than_small_history():
    small, _ = stage_probability("QUOTE_SENT", {"QUOTE_SENT": {"resolved": 8, "win_rate": 0.80}})
    large, _ = stage_probability("QUOTE_SENT", {"QUOTE_SENT": {"resolved": 80, "win_rate": 0.80}})
    assert 0.40 < small < large < 0.80



def test_dashboard_page_contains_management_sections():
    from pathlib import Path

    html_source = Path("app/admin_ui/pages/revenue_forecast.py").read_text(encoding="utf-8")
    assert "Meta e desempenho comercial" in html_source
    assert "Progresso da meta" in html_source
    assert "Ações de maior impacto" in html_source
    assert "Próximos 30 dias adicionais" in html_source
