"""GCP Security Command Center v2 cross-validation client.

Contract:
- GCPCrossValidator extends CloudIntelligenceAnalyzer.
- analyze() fetches SCC active findings and cross-validates against ComplyForm findings.
- 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_scc_resource,
)

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

__all__ = ["GCPCrossValidator"]


class GCPCrossValidator(CloudIntelligenceAnalyzer):
    """GCP Security Command Center v2 ListFindings client.

    SDK: google-cloud-securitycenter v2 or httpx + google-auth.
    Endpoint: POST .../organizations/{org}/sources/-/findings:list
    Filter: state="ACTIVE" AND category!="OPEN_FIREWALL", severity DESC, pageSize 1000.
    """

    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 SCC API access."""
        issues: list[str] = []
        try:
            from google.cloud import (  # type: ignore
                securitycenter_v2,  # noqa: F401
            )
        except ImportError:
            issues.append(
                "google-cloud-securitycenter not installed:"
                " pip install google-cloud-securitycenter"
            )
        return issues

    def analyze(self) -> CloudIntelligenceResult:
        """Fetch SCC findings 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="scc",
                **kwargs,  # type: ignore[arg-type]
            )

        try:
            from google.api_core.exceptions import (  # type: ignore
                NotFound,
                PermissionDenied,
                ResourceExhausted,
            )
            from google.cloud import securitycenter_v2  # type: ignore[attr-defined]
        except ImportError:
            return _result(False, error="google-cloud-securitycenter not installed")

        try:
            client = securitycenter_v2.SecurityCenterClient(
                credentials=self.credentials,
            )
            parent = f"projects/{self.project_id}/sources/-/locations/-"
            request = securitycenter_v2.ListFindingsRequest(
                parent=parent,
                filter_='state="ACTIVE"',
                page_size=1000,
            )
            native_findings: list[NativeFinding] = []
            for finding_result in client.list_findings(request=request):
                f = finding_result.finding
                rtype = f.resource_name.split("/")[2] if "/" in f.resource_name else ""
                sev = (
                    f.severity.name if hasattr(f.severity, "name") else str(f.severity)
                )
                native_findings.append(
                    NativeFinding(
                        native_id=f.category,
                        resource_id=f.resource_name,
                        resource_type=rtype,
                        severity=sev,
                        title=f.category,
                        status="ACTIVE",
                    )
                )
        except PermissionDenied:
            return _result(
                False,
                error="Missing roles/securitycenter.findingsViewer",
            )
        except NotFound:
            return _result(
                False,
                error="Security Command Center not enabled",
            )
        except ResourceExhausted:
            # Retry once
            try:
                time.sleep(1)
                native_findings = []
                for finding_result in client.list_findings(request=request):
                    f = finding_result.finding
                    rtype = (
                        f.resource_name.split("/")[2] if "/" in f.resource_name else ""
                    )
                    sev = (
                        f.severity.name
                        if hasattr(f.severity, "name")
                        else str(f.severity)
                    )
                    native_findings.append(
                        NativeFinding(
                            native_id=f.category,
                            resource_id=f.resource_name,
                            resource_type=rtype,
                            severity=sev,
                            title=f.category,
                            status="ACTIVE",
                        )
                    )
            except Exception:
                return _result(False, error="SCC API rate limited")
        except Exception as exc:
            return _result(False, error=str(exc))

        def _normalize(resource_id: str, resource_type: str) -> str | None:
            return normalize_scc_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,
        )
