"""End-to-end cloud intelligence integration tests.

Full flow: scan -> assess with CI -> dashboard push.
All cloud APIs mocked.
"""

from __future__ import annotations

import dataclasses
import json
from typing import TYPE_CHECKING, Any

from complyform.core.cloud_intelligence.cost_estimator import CostImpactEstimate
from complyform.core.cloud_intelligence.cross_validator import CrossValidationResult
from complyform.core.cloud_intelligence.iam_analyzer import (
    IAMAnalysisResult,
    IAMFinding,
)
from complyform.core.scanner.landing_zone import LandingZoneContext

if TYPE_CHECKING:
    from pathlib import Path


def _make_iam_finding() -> IAMFinding:
    return IAMFinding(
        cloud="gcp",
        principal="sa@proj.iam.gserviceaccount.com",
        principal_type="service_account",
        current_role="roles/editor",
        recommended_role="roles/viewer",
        unused_permissions=["storage.buckets.delete"],
        last_activity="2025-01-01T00:00:00Z",
        risk_level="HIGH",
        framework_controls=[{"framework": "soc2", "control_id": "CC6.1"}],
        remediation_terraform=None,
        source_api="iam_recommender",
    )


def _make_landing_zone() -> LandingZoneContext:
    return LandingZoneContext(
        cloud="gcp",
        detected=True,
        type="assured_workloads",
        inherited_policies=["policy-encrypt-at-rest", "policy-vpc-sc"],
        compliance_regime="fedramp",
    )


def _make_all_ci_results() -> dict[str, Any]:
    """Create all CI results as dicts (like cache metadata)."""
    iam = IAMAnalysisResult(
        feature="iam_analysis",
        cloud="gcp",
        success=True,
        error=None,
        duration_ms=100,
        timestamp="2025-01-01T00:00:00Z",
        findings=[_make_iam_finding()],
        principals_scanned=10,
        over_provisioned_count=1,
        unused_role_count=0,
    )
    xval = CrossValidationResult(
        feature="cross_validation",
        cloud="gcp",
        success=True,
        error=None,
        duration_ms=200,
        timestamp="2025-01-01T00:00:00Z",
        cross_validation_score=85,
        native_tool="scc",
    )
    cost = CostImpactEstimate(
        feature="cost_impact",
        cloud="gcp",
        success=True,
        error=None,
        duration_ms=150,
        timestamp="2025-01-01T00:00:00Z",
        total_monthly_delta=42.0,
        total_annual_delta=504.0,
        confidence="estimated",
    )
    lz = _make_landing_zone()

    return {
        "iam_analysis": dataclasses.asdict(iam),
        "cross_validation": dataclasses.asdict(xval),
        "cost_impact": dataclasses.asdict(cost),
        "landing_zone": dataclasses.asdict(lz),
    }


class TestE2EFlow:
    """Full flow integration test with all APIs mocked."""

    def test_ci_results_roundtrip_via_cache_metadata(self, tmp_path: Path) -> None:
        """CI results written to cache metadata survive serialization."""
        ci_data = _make_all_ci_results()

        # Write to "cache"
        meta_path = tmp_path / "metadata.json"
        meta: dict[str, Any] = {
            "scanned_at": "2025-01-01T00:00:00Z",
            "cloud": "gcp",
            "state_hash": "sha256:abc123",
        }
        meta.update(ci_data)
        meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")

        # Read back
        loaded = json.loads(meta_path.read_text(encoding="utf-8"))

        assert loaded["iam_analysis"]["success"] is True
        assert loaded["iam_analysis"]["principals_scanned"] == 10
        assert loaded["cross_validation"]["cross_validation_score"] == 85
        assert loaded["cost_impact"]["total_monthly_delta"] == 42.0
        assert loaded["landing_zone"]["detected"] is True
        assert loaded["landing_zone"]["type"] == "assured_workloads"

    def test_dashboard_payload_includes_all_ci_sections(self) -> None:
        """Dashboard push payload includes cloud_intelligence when CI data present."""
        from complyform.cli.dashboard_cmd import _build_cloud_intelligence_payload

        metadata = {
            "scanned_at": "2025-01-01T00:00:00Z",
            "cloud": "gcp",
        }
        metadata.update(_make_all_ci_results())

        ci_payload = _build_cloud_intelligence_payload(metadata)

        assert "iam_analysis" in ci_payload
        assert ci_payload["iam_analysis"]["principals_scanned"] == 10
        assert ci_payload["iam_analysis"]["over_provisioned_count"] == 1

        assert "cross_validation" in ci_payload
        assert ci_payload["cross_validation"]["score"] == 85
        assert ci_payload["cross_validation"]["native_tool"] == "scc"

        assert "cost_impact" in ci_payload
        assert ci_payload["cost_impact"]["total_monthly_delta"] == 42.0

        assert "landing_zone" in ci_payload
        assert ci_payload["landing_zone"]["detected"] is True
        assert ci_payload["landing_zone"]["type"] == "assured_workloads"
        assert ci_payload["landing_zone"]["inherited_policies_count"] == 2

    def test_dashboard_payload_empty_when_no_ci(self) -> None:
        """Dashboard push has no cloud_intelligence when no CI data."""
        from complyform.cli.dashboard_cmd import _build_cloud_intelligence_payload

        metadata: dict[str, Any] = {
            "scanned_at": "2025-01-01T00:00:00Z",
            "cloud": "gcp",
        }
        ci_payload = _build_cloud_intelligence_payload(metadata)
        assert ci_payload == {}

    def test_ci_results_dont_affect_exit_code(self) -> None:
        """CI results don't change exit code — only compliance failures do."""
        from complyform.cli.exit_codes import (
            EXIT_COMPLIANCE_FAILURE,
            EXIT_SUCCESS,
        )

        # Compliance failures determine exit code, not CI results
        has_failures = True
        exit_code = EXIT_COMPLIANCE_FAILURE if has_failures else EXIT_SUCCESS
        assert exit_code == EXIT_COMPLIANCE_FAILURE

        has_failures = False
        exit_code = EXIT_COMPLIANCE_FAILURE if has_failures else EXIT_SUCCESS
        assert exit_code == EXIT_SUCCESS

    def test_landing_zone_detection_result(self) -> None:
        """Landing zone detection returns LandingZoneContext."""
        lz = _make_landing_zone()
        assert lz.detected is True
        assert lz.type == "assured_workloads"
        assert len(lz.inherited_policies) == 2
        assert lz.compliance_regime == "fedramp"

    def test_partial_ci_results_still_pushed(self) -> None:
        """Only some CI features available -> only those in payload."""
        from complyform.cli.dashboard_cmd import _build_cloud_intelligence_payload

        metadata: dict[str, Any] = {
            "cloud": "gcp",
            "iam_analysis": dataclasses.asdict(
                IAMAnalysisResult(
                    feature="iam_analysis",
                    cloud="gcp",
                    success=True,
                    error=None,
                    duration_ms=100,
                    timestamp="2025-01-01T00:00:00Z",
                    findings=[],
                    principals_scanned=5,
                    over_provisioned_count=0,
                    unused_role_count=0,
                )
            ),
            "cross_validation": dataclasses.asdict(
                CrossValidationResult(
                    feature="cross_validation",
                    cloud="gcp",
                    success=False,
                    error="SCC unavailable",
                    duration_ms=10,
                    timestamp="2025-01-01T00:00:00Z",
                )
            ),
        }

        ci_payload = _build_cloud_intelligence_payload(metadata)
        # IAM succeeded -> present
        assert "iam_analysis" in ci_payload
        # Cross-validation failed -> not present
        assert "cross_validation" not in ci_payload
        # Cost/LZ not run -> not present
        assert "cost_impact" not in ci_payload
        assert "landing_zone" not in ci_payload
