from __future__ import annotations

from src.api.v1.webhooks import (
    AlertmanagerAlert,
    _cicd_duration_seconds_from_alert,
    _cicd_job_status_from_alert,
)
from src.services.telegram_gateway import CICDProgressMessage


def test_cicd_alert_status_label_overrides_severity() -> None:
    alert = AlertmanagerAlert(
        status="firing",
        labels={"status": "failed", "severity": "info"},
        annotations={},
    )

    assert _cicd_job_status_from_alert(alert) == "failed"


def test_cicd_alert_legacy_info_severity_remains_success() -> None:
    alert = AlertmanagerAlert(
        status="firing",
        labels={"severity": "info"},
        annotations={},
    )

    assert _cicd_job_status_from_alert(alert) == "success"


def test_cicd_alert_duration_is_sanitized() -> None:
    assert _cicd_duration_seconds_from_alert(
        AlertmanagerAlert(
            status="firing",
            labels={"duration_seconds": "91"},
            annotations={},
        )
    ) == 91
    assert _cicd_duration_seconds_from_alert(
        AlertmanagerAlert(
            status="firing",
            labels={"duration_seconds": "-5"},
            annotations={},
        )
    ) == 0


def test_cicd_progress_message_includes_safe_detail() -> None:
    message = CICDProgressMessage(
        job_name="Code Review",
        status="failed",
        stage="review",
        commit_sha="abcdef1234567890",
        message="最高風險 <script> & 需人工複核",
        workflow_url="http://192.168.0.110:3001/wooo/awoooi/actions",
    ).format()

    assert "❌" in message
    assert "Code Review" in message
    assert "abcdef12" in message
    assert "最高風險 &lt;script&gt; &amp; 需人工複核" in message
    assert "<script>" not in message
