from __future__ import annotations

import pytest

from src.services.agent_claude_remediator_adapter import (
    CLAUDE_REMEDIATOR_CANDIDATE_ID,
    build_claude_remediator_candidate_result,
)


def test_claude_remediator_adapter_emits_candidate_result_contract():
    result = build_claude_remediator_candidate_result({
        "schema_version": "agent_replay_candidate_input_v1",
        "run_id": "run",
        "incident_id": "INC-1",
        "incident_context": {
            "severity": "P2",
            "alert_category": "backend",
            "alertname": "FastAPIImportError",
            "affected_services": ["awoooi-api"],
            "signals": [
                {
                    "labels": {"service": "awoooi-api"},
                    "annotations": {"summary": "ImportError traceback in API build"},
                }
            ],
        },
        "source_metadata": {},
    }).to_dict()

    assert result["schema_version"] == "agent_candidate_replay_result_v1"
    assert result["candidate_id"] == CLAUDE_REMEDIATOR_CANDIDATE_ID
    assert result["candidate_role"] == "devops_code_remediation_agent"
    assert "CLAUDE_PATCH_PROPOSAL" in result["proposed_action"]
    assert result["risk_level"] == "medium"
    assert result["requires_human_approval"] is True
    assert result["fallback_used"] is False
    assert result["trace_complete"] is True
    assert result["cost_usd"] == 0
    assert result["metadata"]["adapter_mode"] == "deterministic_offline_remediation_boundary"
    assert result["metadata"]["anthropic_api_calls"] is False
    assert result["metadata"]["files_edited"] is False


def test_claude_remediator_adapter_rejects_label_leak_before_execution():
    with pytest.raises(ValueError, match="evaluation label"):
        build_claude_remediator_candidate_result({
            "run_id": "run",
            "incident_id": "INC-1",
            "incident_context": {
                "execution_success": True,
            },
            "source_metadata": {},
        })


def test_claude_remediator_adapter_routes_config_to_secret_safe_review():
    result = build_claude_remediator_candidate_result({
        "schema_version": "agent_replay_candidate_input_v1",
        "run_id": "run",
        "incident_id": "INC-2",
        "incident_context": {
            "severity": "P3",
            "alert_category": "config",
            "alertname": "TelegramTokenMisconfigured",
            "affected_services": ["awoooi-api"],
            "signals": [{"annotations": {"summary": "secret token config changed"}}],
        },
        "source_metadata": {},
    }).to_dict()

    assert "CLAUDE_CONFIG_REVIEW" in result["proposed_action"]
    assert result["risk_level"] == "high"
    assert result["requires_human_approval"] is True
    assert result["metadata"]["remediation_route"] == "config_patch_proposal"
    assert result["metadata"]["anthropic_api_calls"] is False
