"""GCP Assured Workloads landing zone detection.

Contract:
- detect_gcp_landing_zone() queries Cloud Asset Inventory for Assured Workloads.
- Never raises — returns LandingZoneContext(detected=False) on error.
"""

from __future__ import annotations

import sys

from complyform.core.scanner.landing_zone import LandingZoneContext

__all__ = ["detect_gcp_landing_zone"]


def detect_gcp_landing_zone(
    project_id: str,
    credentials: object | None,
) -> LandingZoneContext:
    """Query CAI for Assured Workloads resources.

    CAI query: search_all_resources with
    asset_types=["assuredworkloads.googleapis.com/Workload"].
    If found: extract compliance_regime, query inherited org policies.
    """
    try:
        from google.cloud import asset_v1  # type: ignore
    except ImportError:
        print(
            "Warning: google-cloud-asset not installed, skipping GCP LZ detection",
            file=sys.stderr,
        )
        return LandingZoneContext(cloud="gcp", detected=False, type=None)

    try:
        client = asset_v1.AssetServiceClient(credentials=credentials)
        scope = f"projects/{project_id}"

        request = asset_v1.SearchAllResourcesRequest(
            scope=scope,
            asset_types=["assuredworkloads.googleapis.com/Workload"],
        )
        results = list(client.search_all_resources(request=request))

        if not results:
            return LandingZoneContext(cloud="gcp", detected=False, type=None)

        # Extract compliance regime from first workload
        workload = results[0]
        compliance_regime: str | None = None
        display_name = workload.display_name or ""
        lower_name = display_name.lower()
        if "fedramp" in lower_name:
            compliance_regime = "fedramp"
        elif "hipaa" in lower_name:
            compliance_regime = "hipaa"
        elif "sovereign" in lower_name or "eu" in lower_name:
            compliance_regime = "eu_sovereign"

        # Extract hierarchy path
        hierarchy: list[str] = []
        if hasattr(workload, "folders"):
            hierarchy = [f.resource_folder for f in workload.folders]
        hierarchy.append(f"projects/{project_id}")

        # Query inherited org policies
        inherited_policies: list[str] = []
        try:
            from google.cloud import orgpolicy_v2  # type: ignore[attr-defined]

            policy_client = orgpolicy_v2.OrgPolicyClient(credentials=credentials)
            request_policies = orgpolicy_v2.ListPoliciesRequest(
                parent=f"projects/{project_id}",
            )
            for policy in policy_client.list_policies(request=request_policies):
                if policy.name:
                    inherited_policies.append(policy.name.split("/")[-1])
        except Exception as exc:
            print(
                f"Warning: could not list org policies: {exc}",
                file=sys.stderr,
            )

        return LandingZoneContext(
            cloud="gcp",
            detected=True,
            type="assured_workloads",
            inherited_policies=inherited_policies,
            compliance_regime=compliance_regime,
            hierarchy_path=hierarchy,
        )

    except Exception as exc:
        print(
            f"Warning: GCP landing zone detection failed: {exc}",
            file=sys.stderr,
        )
        return LandingZoneContext(cloud="gcp", detected=False, type=None)
