# -*- coding: utf-8 -*-
"""
AR-84 Antiforgery & Cryptographic Provenance Gates (Scenarios A through I)
Tests negative adversarial scenarios trying to breach promotion gates with fake or tampered telemetry.
"""
import copy
import os
import shutil
import sys
import tempfile
from pathlib import Path

# Ensure candidate_workspace takes precedence over production
_LAB_DIR = Path(__file__).resolve().parents[1]
_CANDIDATE_WS = str(_LAB_DIR / "candidate_workspace")
if _CANDIDATE_WS not in sys.path:
    sys.path.insert(0, _CANDIDATE_WS)

import pytest

from app.remediation.self_repair.telemetry_contract import (
    AuthenticTelemetryEvaluator,
    TelemetryAuditRecord,
    get_supervisor_telemetry_key,
    reset_consumed_nonces,
)
from app.remediation.self_repair.promotion_guard import PromotionGuard
from app.remediation.self_repair.promotion_executor import PromotionExecutor
from app.remediation.self_repair.schemas import CandidateVerdict


@pytest.fixture
def test_env():
    reset_consumed_nonces()
    temp_dir = tempfile.mkdtemp(prefix="ar84_test_ws_")
    ws_p = Path(temp_dir).resolve()
    
    # Create a non-critical test target file
    target_rel = "app/modules/demo_module.py"
    target_full = ws_p / target_rel
    target_full.parent.mkdir(parents=True, exist_ok=True)
    target_full.write_text("def demo():\n    return 42\n", encoding="utf-8")
    
    # Create backup for rollback
    backup_full = ws_p / "app/modules/demo_module.py.bak"
    backup_full.write_text("def demo():\n    return 42\n", encoding="utf-8")
    
    rollback_plan = {
        "backup_file": str(backup_full),
        "source_sha256": "any",
    }
    
    yield {
        "ws_root": str(ws_p),
        "target_file": str(target_full),
        "target_rel": target_rel,
        "rollback_plan": rollback_plan,
    }
    
    shutil.rmtree(temp_dir, ignore_errors=True)


def test_scenario_a_recalculated_sha256_without_supervisor_secret(test_env):
    """A. Recalculated signature without supervisor secret fails closed."""
    ws = test_env["ws_root"]
    rec = AuthenticTelemetryEvaluator.evaluate_telemetry(
        mission_id="m_scen_a",
        instance_id="inst_a",
        workspace_root=ws,
        observer_active=True,
        monitored_scopes=["URLLIB_HTTP", "RAW_SOCKET"],
        detected_attempts=[],
        supervisor_key=b"unauthorized_secret_key_12345678",
    )
    # verify against trusted supervisor key
    is_valid, reason = rec.verify_authenticity(
        expected_mission_id="m_scen_a",
        expected_workspace_root=ws,
    )
    assert is_valid is False
    assert reason == "HMAC_SIGNATURE_MISMATCH"

    guard = PromotionGuard(ws)
    assert not guard.validate_provider_safety(
        provider_called="FALSE_VERIFIED",
        network_used="FALSE_VERIFIED",
        telemetry_audit=rec,
        expected_mission_id="m_scen_a",
        expected_workspace_root=ws,
    )


def test_scenario_b_reused_record_from_another_mission(test_env):
    """B. Reused record from another mission_id fails closed."""
    ws = test_env["ws_root"]
    rec = AuthenticTelemetryEvaluator.evaluate_telemetry(
        mission_id="original_mission_111",
        instance_id="inst_b",
        workspace_root=ws,
        observer_active=True,
        monitored_scopes=["URLLIB_HTTP", "RAW_SOCKET"],
        detected_attempts=[],
    )
    is_valid, reason = rec.verify_authenticity(
        expected_mission_id="different_mission_999",
        expected_workspace_root=ws,
    )
    assert is_valid is False
    assert "MISSION_ID_MISMATCH" in reason

    guard = PromotionGuard(ws)
    assert not guard.validate_provider_safety(
        provider_called="FALSE_VERIFIED",
        network_used="FALSE_VERIFIED",
        telemetry_audit=rec,
        expected_mission_id="different_mission_999",
        expected_workspace_root=ws,
    )


def test_scenario_c_altered_execution_interval(test_env):
    """C. Tampered interval timestamps break HMAC signature."""
    ws = test_env["ws_root"]
    rec = AuthenticTelemetryEvaluator.evaluate_telemetry(
        mission_id="m_scen_c",
        instance_id="inst_c",
        workspace_root=ws,
        observer_active=True,
        monitored_scopes=["URLLIB_HTTP", "RAW_SOCKET"],
        detected_attempts=[],
    )
    # Tamper interval_end
    rec.interval_end = "2026-10-27T99:99:99Z"
    is_valid, reason = rec.verify_authenticity(
        expected_mission_id="m_scen_c",
        expected_workspace_root=ws,
    )
    assert is_valid is False
    assert reason == "HMAC_SIGNATURE_MISMATCH"


def test_scenario_d_mismatched_workspace_root(test_env):
    """D. Mismatched workspace_root fails closed."""
    ws = test_env["ws_root"]
    rec = AuthenticTelemetryEvaluator.evaluate_telemetry(
        mission_id="m_scen_d",
        instance_id="inst_d",
        workspace_root="C:/another/workspace",
        observer_active=True,
        monitored_scopes=["URLLIB_HTTP", "RAW_SOCKET"],
        detected_attempts=[],
    )
    is_valid, reason = rec.verify_authenticity(
        expected_mission_id="m_scen_d",
        expected_workspace_root=ws,
    )
    assert is_valid is False
    assert "WORKSPACE_ROOT_MISMATCH" in reason


def test_scenario_e_repeated_replayed_nonce(test_env):
    """E. Repeated/replayed nonce/signature is rejected on second use."""
    ws = test_env["ws_root"]
    rec = AuthenticTelemetryEvaluator.evaluate_telemetry(
        mission_id="m_scen_e",
        instance_id="inst_e",
        workspace_root=ws,
        observer_active=True,
        monitored_scopes=["URLLIB_HTTP", "RAW_SOCKET"],
        detected_attempts=[],
    )
    # First check: passes
    ok1, _ = rec.verify_authenticity(
        expected_mission_id="m_scen_e",
        expected_workspace_root=ws,
        enforce_replay_guard=True,
    )
    assert ok1 is True

    # Replay check: fails
    ok2, reason2 = rec.verify_authenticity(
        expected_mission_id="m_scen_e",
        expected_workspace_root=ws,
        enforce_replay_guard=True,
    )
    assert ok2 is False
    assert reason2 == "REPLAYED_TELEMETRY_RECORD"


def test_scenario_f_injected_false_verified_in_error_context(test_env):
    """F. Injected FALSE_VERIFIED in error_context without signed audit blocks promotion."""
    ws = test_env["ws_root"]
    from app.remediation.self_repair.schemas import MissionFailureSnapshot
    from app.remediation.self_repair.shadow_orchestrator import ShadowSelfRepairOrchestrator

    snap = MissionFailureSnapshot(
        mission_id="m_scen_f",
        instance_id="inst_f",
        workspace_root=ws,
        creator_request="test",
        mission_status="FAILED",
        failure_stage="execute",
        source_component="test",
        error_context={"provider_called": "FALSE_VERIFIED", "network_used": "FALSE_VERIFIED"},
    )

    orch = ShadowSelfRepairOrchestrator(project_root=ws)
    prov, net, tele_reason = orch.reconcile_telemetry(snap, repair_res={}, require_authenticated_provenance=True)
    assert tele_reason == "UNKNOWN_TELEMETRY"
    assert prov is None or prov is True


def test_scenario_g_direct_execute_promotion_bypass(test_env):
    """G. FALSE_VERIFIED passed directly to PromotionExecutor without audit blocks promotion."""
    ws = test_env["ws_root"]
    guard = PromotionGuard(workspace_root=ws)
    executor = PromotionExecutor(guard=guard)
    
    # Try calling execute_promotion directly with FALSE_VERIFIED and no telemetry_audit
    res = executor.execute_promotion(
        target_file=test_env["target_file"],
        patch_candidate=None,
        workspace_root=ws,
        confidence="HIGH",
        root_cause_proven=True,
        sandbox_verdict=CandidateVerdict(
            verdict="ACCEPT",
            candidate_id="cand_1",
            incident_id="inc_1",
            repair_id="rep_1",
            root_cause_proven=True,
            compile_pass=True,
            focused_tests_pass=True,
            regression_tests_pass=True,
            baseline_integrity=True,
            production_untouched=True,
            patch_applied=True,
        ),
        focused_tests_pass=True,
        regression_tests_pass=True,
        rollback_ready=True,
        rollback_plan=test_env["rollback_plan"],
        provider_called="FALSE_VERIFIED",
        network_used="FALSE_VERIFIED",
        telemetry_audit=None,
        require_authenticated_provenance=True,
    )
    assert res.promotion_verified is False
    assert res.decision.promotion_allowed is False
    assert "UNKNOWN_TELEMETRY" in res.decision.reason_code or "BLOCKED" in res.error_message


def test_scenario_h_inactive_observer(test_env):
    """H. Inactive observer fails closed."""
    ws = test_env["ws_root"]
    rec = AuthenticTelemetryEvaluator.evaluate_telemetry(
        mission_id="m_scen_h",
        instance_id="inst_h",
        workspace_root=ws,
        observer_active=False,
        monitored_scopes=["URLLIB_HTTP", "RAW_SOCKET"],
        detected_attempts=[],
    )
    assert rec.provider_status == "UNKNOWN"
    assert rec.promotion_eligible is False

    is_valid, reason = rec.verify_authenticity(
        expected_mission_id="m_scen_h",
        expected_workspace_root=ws,
    )
    assert is_valid is False
    assert reason == "OBSERVER_INACTIVE"


def test_scenario_i_partial_scope_coverage_missing_raw_socket(test_env):
    """I. Partial scope coverage (missing RAW_SOCKET) fails closed."""
    ws = test_env["ws_root"]
    rec = AuthenticTelemetryEvaluator.evaluate_telemetry(
        mission_id="m_scen_i",
        instance_id="inst_i",
        workspace_root=ws,
        observer_active=True,
        monitored_scopes=["URLLIB_HTTP"],  # Missing RAW_SOCKET
        detected_attempts=[],
    )
    assert rec.provider_status == "UNKNOWN"
    assert rec.promotion_eligible is False

    is_valid, reason = rec.verify_authenticity(
        expected_mission_id="m_scen_i",
        expected_workspace_root=ws,
    )
    assert is_valid is False
    assert reason == "INCOMPLETE_SCOPE_COVERAGE"
