from pathlib import Path

from app.admin_ui.labels import primary_action_label
from app.admin_ui.view_models.operations import (
    is_association_review,
    operation_due_label,
    operation_status_chip,
)
from app.operations_service import _normalise_work_item_intent
from app.revenue_forecast_service import management_status


def test_followup_payment_has_human_label():
    assert primary_action_label("FOLLOW_UP_PAYMENT") == "Follow-up de pagamento"


def test_reconciliation_candidate_becomes_first_safe_decision():
    item = {
        "action_code": "SEND_PROFORMA",
        "source_system": "jasmin",
        "detail": "Documento encontrado via API Jasmin. Operador deve ligar a oportunidade existente, criar oportunidade ou ignorar.",
        "title": "Orçamento Jasmin sem oportunidade · ORC.1",
        "opportunity_linking_status": "review_required",
        "opportunity_metadata": {},
    }
    result = _normalise_work_item_intent([item])[0]
    assert result["action_code"] == "ASSOCIATE_OPPORTUNITY"
    assert result["queue"] == "rever"
    assert is_association_review(result)
    assert operation_status_chip(result) == "associação por confirmar"


def test_reconstructed_financial_action_requires_review():
    item = {
        "action_code": "CONFIRM_PAYMENT",
        "opportunity_metadata": {
            "clientflow_record_mode": "historical_reconstructed",
            "reconstructed_review_status": "required",
        },
    }
    result = _normalise_work_item_intent([item])[0]
    assert result["action_code"] == "REVIEW_RECONSTRUCTED_PROCESS"
    assert operation_status_chip(result) == "validação obrigatória"


def test_due_label_exposes_overdue_state():
    assert "Vencida" in operation_due_label({"due_at": "2020-01-01T00:00:00+00:00"})


def test_management_status_supports_recoverable_target():
    status = management_status(target=10000, forecast_total=8200, quality_score=0.48, recoverable_total=2400)
    assert status["code"] == "recoverable"
    assert status["label"] == "Meta recuperável"


def test_forecast_has_canonical_route_and_legacy_redirects():
    source = Path("app/admin_ui/pages/revenue_forecast.py").read_text(encoding="utf-8")
    assert '@router.get("/forecast"' in source
    assert '@router.get("/finance/forecast")' in source
    assert 'RedirectResponse(f"/forecast?' in source


def test_dashboard_and_navigation_include_forecast():
    dashboard = Path("app/admin_ui/pages/dashboard.py").read_text(encoding="utf-8")
    navigation = Path("app/admin_ui/navigation.py").read_text(encoding="utf-8")
    assert "Visão executiva" in dashboard
    assert 'NavItem("forecast", "/forecast"' in navigation
