"""Tests for SCC v2 NDJSON exporter."""

from __future__ import annotations

import json
from typing import TYPE_CHECKING

import pytest

from complyform.core.generators.evidence_export.scc_json import SccJsonExporter

if TYPE_CHECKING:
    from pathlib import Path


@pytest.fixture
def exporter() -> SccJsonExporter:
    return SccJsonExporter()


@pytest.fixture
def sample_findings() -> list[dict[str, object]]:
    return [
        {
            "control_id": "CC6.1",
            "framework": "soc2",
            "resource_address": "google_sql_database_instance.main",
            "resource_type": "google_sql_database_instance",
            "status": "FAIL",
            "severity": "CRITICAL",
            "finding": "Encryption not enabled",
            "remediation": "Enable encryption",
            "checkov_id": "CKV_GCP_6",
            "native_ids": {"scc": "SQL_CMEK_DISABLED"},
            "cross_mappings": [{"framework": "hipaa", "control_id": "164.312"}],
            "confidence": "verified",
        },
    ]


@pytest.fixture
def metadata() -> dict[str, object]:
    return {
        "scan_id": "abc12345",
        "timestamp": "2024-01-01T00:00:00Z",
        "cloud": "gcp",
    }


class TestSccJsonExporter:
    def test_format_id(self, exporter: SccJsonExporter) -> None:
        assert exporter.FORMAT_ID == "scc-json"
        assert exporter.TIER_FEATURE == "evidence_export_native"

    def test_valid_ndjson(
        self,
        exporter: SccJsonExporter,
        sample_findings: list[dict[str, object]],
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        result = exporter.export_to_file(sample_findings, metadata, tmp_path)
        ndjson_files = [f for f in result.output_files if f.suffix == ".ndjson"]
        assert len(ndjson_files) == 1
        content = ndjson_files[0].read_text()
        for line in content.strip().split("\n"):
            parsed = json.loads(line)
            assert "findingId" in parsed
            assert "finding" in parsed

    def test_finding_id_format(
        self,
        exporter: SccJsonExporter,
        sample_findings: list[dict[str, object]],
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        result = exporter.export_to_file(sample_findings, metadata, tmp_path)
        ndjson_files = [f for f in result.output_files if f.suffix == ".ndjson"]
        content = ndjson_files[0].read_text()
        record = json.loads(content.strip().split("\n")[0])
        assert record["findingId"].startswith("cf-CC6.1-")
        assert len(record["findingId"].split("-")[-1]) == 8

    def test_severity_mapping(
        self,
        exporter: SccJsonExporter,
        sample_findings: list[dict[str, object]],
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        result = exporter.export_to_file(sample_findings, metadata, tmp_path)
        ndjson_files = [f for f in result.output_files if f.suffix == ".ndjson"]
        record = json.loads(ndjson_files[0].read_text().strip())
        assert record["finding"]["severity"] == "CRITICAL"

    def test_state_active_for_fail(
        self,
        exporter: SccJsonExporter,
        sample_findings: list[dict[str, object]],
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        result = exporter.export_to_file(sample_findings, metadata, tmp_path)
        ndjson_files = [f for f in result.output_files if f.suffix == ".ndjson"]
        record = json.loads(ndjson_files[0].read_text().strip())
        assert record["finding"]["state"] == "ACTIVE"

    def test_pass_excluded_by_default(
        self,
        exporter: SccJsonExporter,
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        findings = [
            {
                "control_id": "CC6.1",
                "framework": "soc2",
                "resource_address": "google_sql_database_instance.main",
                "resource_type": "google_sql_database_instance",
                "status": "FAIL",
                "severity": "CRITICAL",
                "finding": "test",
                "remediation": "",
                "checkov_id": None,
                "native_ids": None,
                "cross_mappings": None,
                "confidence": "high",
            },
        ]
        result = exporter.export_to_file(findings, metadata, tmp_path)
        assert result.record_count == 1

    def test_pass_included(
        self,
        exporter: SccJsonExporter,
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        findings = [
            {
                "control_id": "CC6.1",
                "framework": "soc2",
                "resource_address": "google_sql_database_instance.main",
                "resource_type": "google_sql_database_instance",
                "status": "PASS",
                "severity": "CRITICAL",
                "finding": "",
                "remediation": "",
                "checkov_id": None,
                "native_ids": None,
                "cross_mappings": None,
                "confidence": "high",
            },
        ]
        result = exporter.export_to_file(findings, metadata, tmp_path)
        assert result.record_count == 1
        ndjson_files = [f for f in result.output_files if f.suffix == ".ndjson"]
        record = json.loads(ndjson_files[0].read_text().strip())
        assert record["finding"]["state"] == "INACTIVE"

    def test_source_properties(
        self,
        exporter: SccJsonExporter,
        sample_findings: list[dict[str, object]],
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        result = exporter.export_to_file(sample_findings, metadata, tmp_path)
        ndjson_files = [f for f in result.output_files if f.suffix == ".ndjson"]
        record = json.loads(ndjson_files[0].read_text().strip())
        props = record["finding"]["sourceProperties"]
        assert "complyform_control_id" in props
        assert "complyform_framework" in props
        assert "complyform_resource_address" in props
        assert "complyform_severity" in props
        assert "complyform_version" in props
        assert "complyform_checkov_id" in props
        assert "complyform_scc_detector" in props

    def test_companion_instructions(
        self,
        exporter: SccJsonExporter,
        sample_findings: list[dict[str, object]],
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        result = exporter.export_to_file(sample_findings, metadata, tmp_path)
        md_files = [f for f in result.output_files if f.suffix == ".md"]
        assert len(md_files) == 1
        assert md_files[0].exists()
