"""Azure Defender for Cloud cross-validation client.

Contract:
- AzureCrossValidator extends CloudIntelligenceAnalyzer.
- analyze() fetches Defender assessments and cross-validates.
- Never raises — returns success=False with descriptive error on failure.
"""

from __future__ import annotations

import time
from datetime import UTC, datetime
from typing import TYPE_CHECKING

from complyform.core.cloud_intelligence import (
    CloudIntelligenceAnalyzer,
    CloudIntelligenceResult,
)
from complyform.core.cloud_intelligence.cross_validator import (
    CrossValidationResult,
    NativeFinding,
    match_findings,
)
from complyform.core.cloud_intelligence.resource_normalizers import (
    normalize_azure_resource,
)

if TYPE_CHECKING:
    from complyform.core.assessor.control_matcher import Finding

__all__ = ["AzureCrossValidator"]


class AzureCrossValidator(CloudIntelligenceAnalyzer):
    """Azure Defender for Cloud Assessments client.

    SDK: azure-mgmt-security.
    Endpoint: GET .../providers/Microsoft.Security/assessments?api-version=2021-06-01
    Filter: status.code == "Unhealthy".
    """

    def __init__(
        self,
        cloud: str,
        project_id: str,
        credentials: object | None = None,
        complyform_findings: list[Finding] | None = None,
    ) -> None:
        super().__init__(cloud, project_id, credentials)
        self.complyform_findings: list[Finding] = complyform_findings or []

    def check_prerequisites(self) -> list[str]:
        """Check Azure Security SDK access."""
        issues: list[str] = []
        try:
            from azure.mgmt.security import (  # type: ignore  # noqa: F401
                SecurityCenter,
            )
        except ImportError:
            issues.append(
                "azure-mgmt-security not installed: pip install azure-mgmt-security"
            )
        return issues

    def analyze(self) -> CloudIntelligenceResult:
        """Fetch Defender assessments and cross-validate."""
        start = time.monotonic()
        ts = datetime.now(tz=UTC).isoformat()

        def _result(
            success: bool,
            error: str | None = None,
            **kwargs: object,
        ) -> CrossValidationResult:
            elapsed = int((time.monotonic() - start) * 1000)
            return CrossValidationResult(
                feature="cross_validation",
                cloud=self.cloud,
                success=success,
                error=error,
                duration_ms=elapsed,
                timestamp=ts,
                native_tool="defender",
                **kwargs,  # type: ignore[arg-type]
            )

        try:
            from azure.core.exceptions import (  # type: ignore
                HttpResponseError,
            )
            from azure.mgmt.security import (
                SecurityCenter,
            )
        except ImportError:
            return _result(False, error="azure-mgmt-security not installed")

        try:
            client = SecurityCenter(
                credential=self.credentials,  # type: ignore[arg-type]
                subscription_id=self.project_id,
            )

            native_findings: list[NativeFinding] = []
            scope = f"/subscriptions/{self.project_id}"
            for assessment in client.assessments.list(
                scope=scope,
            ):
                status_code = ""
                if hasattr(assessment, "status") and hasattr(assessment.status, "code"):
                    status_code = assessment.status.code
                if status_code != "Unhealthy":
                    continue

                resource_id = assessment.id or ""
                # Extract assessed resource ID from assessment
                # path: /subscriptions/.../assessments/{id}
                assessed_resource = ""
                if hasattr(assessment, "resource_details"):
                    details = assessment.resource_details
                    if hasattr(details, "id"):
                        assessed_resource = details.id or ""

                display_name = ""
                if hasattr(assessment, "display_name"):
                    display_name = assessment.display_name or ""

                severity_val = "MEDIUM"
                if hasattr(assessment, "metadata") and hasattr(
                    assessment.metadata, "severity"
                ):
                    severity_val = str(assessment.metadata.severity).upper()

                native_findings.append(
                    NativeFinding(
                        native_id=assessment.name or "",
                        resource_id=assessed_resource or resource_id,
                        resource_type=assessed_resource,
                        severity=severity_val,
                        title=display_name,
                        status="Unhealthy",
                    )
                )

        except HttpResponseError as exc:
            return _result(False, error=str(exc))
        except Exception as exc:
            return _result(False, error=str(exc))

        def _normalize(resource_id: str, resource_type: str) -> str | None:
            return normalize_azure_resource(resource_id)

        result = match_findings(self.complyform_findings, native_findings, _normalize)
        return _result(
            success=True,
            total_complyform_findings=result.total_complyform_findings,
            total_native_findings=result.total_native_findings,
            confirmed=result.confirmed,
            complyform_only=result.complyform_only,
            native_only=result.native_only,
            cross_validation_score=result.cross_validation_score,
        )
