from src.services.openclaw import OpenClawService, _build_alert_cache_context_hash


def test_openclaw_cache_key_uses_stable_alert_scope_when_context_hash_exists():
    service = object.__new__(OpenClawService)
    context_hash = "HostBackupFailed:backup_failure:awoooi-prod:awoooi-frequent:critical:fp-1"
    prompt_a = "System prompt and instructions\n\n## Alert Data:\ncurrent_value=1"
    prompt_b = "System prompt and instructions\n\n## Alert Data:\ncurrent_value=2"

    assert service._generate_cache_key(prompt_a, context_hash) == service._generate_cache_key(
        prompt_b,
        context_hash,
    )


def test_openclaw_cache_key_keeps_full_prompt_specificity_without_context_hash():
    service = object.__new__(OpenClawService)
    prompt_a = "System prompt and instructions\n\n## Alert Data:\ncurrent_value=1"
    prompt_b = "System prompt and instructions\n\n## Alert Data:\ncurrent_value=2"

    assert service._generate_cache_key(prompt_a) != service._generate_cache_key(prompt_b)


def test_openclaw_alert_cache_context_hash_ignores_dynamic_annotations():
    base_context = {
        "alertname": "HostBackupFailed",
        "alert_category": "backup_failure",
        "namespace": "awoooi-prod",
        "target_resource": "awoooi-frequent",
        "severity": "critical",
        "fingerprint": "fp-1",
        "annotations": {"description": "failed at 14:00"},
    }
    next_context = {
        **base_context,
        "annotations": {"description": "failed at 14:01"},
        "message": "new volatile message",
    }

    assert _build_alert_cache_context_hash(base_context) == _build_alert_cache_context_hash(
        next_context
    )
