def test_update_verdict_valid_value(client, mock_db, auth_token):
    response = client.patch(
        "/api/alerts/5/verdict",
        json={"verdict": "true_positive", "reviewed_by": "areej"},
        headers={"Authorization": f"Bearer {auth_token}"}
    )
    assert response.status_code == 200
    assert response.json()["verdict"] == "true_positive"


def test_update_verdict_invalid_value_rejected(client, auth_token):
    response = client.patch(
        "/api/alerts/5/verdict",
        json={"verdict": "maybe"},
        headers={"Authorization": f"Bearer {auth_token}"}
    )
    assert response.status_code == 400


def test_update_verdict_without_token_rejected(client):
    response = client.patch(
        "/api/alerts/5/verdict",
        json={"verdict": "true_positive"}
    )
    assert response.status_code == 401


def test_model_performance_recommends_retrain_on_low_precision(client, mock_db):
    # tp=15, fp=10 -> reviewed=25 (>= RETRAIN_MIN_REVIEWED=20)
    # precision = 15/25 = 0.60 (< RETRAIN_PRECISION_THRESHOLD=0.85)
    mock_db.fetchone.return_value = (15, 10, 5)  # tp, fp, pending
    mock_db.fetchall.return_value = []           # by_attack_type breakdown

    response = client.get("/api/model/performance")

    assert response.status_code == 200
    body = response.json()
    assert body["retraining"]["recommended"] is True
    assert body["live_stats"]["overall_precision"] == 0.6


def test_model_performance_no_retrain_when_precision_good(client, mock_db):
    # tp=95, fp=5 -> reviewed=100, precision=0.95 (above threshold)
    # pending=10 (below RETRAIN_SAMPLE_THRESHOLD=200)
    mock_db.fetchone.return_value = (95, 5, 10)
    mock_db.fetchall.return_value = []

    response = client.get("/api/model/performance")

    assert response.status_code == 200
    body = response.json()
    assert body["retraining"]["recommended"] is False


def test_model_performance_recommends_retrain_on_pending_backlog(client, mock_db):
    # precision is fine (tp=95, fp=5 -> 0.95) but pending alerts exceed threshold
    mock_db.fetchone.return_value = (95, 5, 250)  # pending=250 > 200
    mock_db.fetchall.return_value = []

    response = client.get("/api/model/performance")

    assert response.status_code == 200
    body = response.json()
    assert body["retraining"]["recommended"] is True
