"""Tests for AWS Audit Manager exporter."""

from __future__ import annotations

import json
from typing import TYPE_CHECKING

import pytest

from complyform.core.generators.evidence_export.audit_manager import (
    AuditManagerExporter,
)

if TYPE_CHECKING:
    from pathlib import Path


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


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


@pytest.fixture
def sample_findings() -> list[dict[str, object]]:
    return [
        {
            "control_id": "CC6.1",
            "framework": "soc2",
            "resource_address": "aws_s3_bucket.example",
            "resource_type": "aws_s3_bucket",
            "status": "FAIL",
            "severity": "HIGH",
            "finding": "Bucket encryption not enabled",
            "remediation": "Enable SSE",
            "checkov_id": "CKV_AWS_19",
            "native_ids": None,
            "cross_mappings": None,
            "confidence": "high",
        }
    ]


class TestAuditManagerExporter:
    def test_format_id(self, exporter: AuditManagerExporter) -> None:
        assert exporter.FORMAT_ID == "audit-manager"
        assert exporter.TIER_FEATURE == "evidence_export_native"

    def test_evidence_text_max_length(
        self,
        exporter: AuditManagerExporter,
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        # Create findings with long text
        findings = []
        for i in range(50):
            findings.append(
                {
                    "control_id": "CC6.1",
                    "framework": "soc2",
                    "resource_address": f"aws_s3_bucket.bucket_{i}",
                    "resource_type": "aws_s3_bucket",
                    "status": "FAIL",
                    "severity": "HIGH",
                    "finding": f"Very long finding description number {i} " * 10,
                    "remediation": "Fix it",
                    "checkov_id": None,
                    "native_ids": None,
                    "cross_mappings": None,
                    "confidence": "high",
                }
            )

        result = exporter.export_to_file(findings, metadata, tmp_path)
        json_files = [f for f in result.output_files if f.suffix == ".json"]
        data = json.loads(json_files[0].read_text())
        for entry in data["control_evidence"]:
            assert len(entry["evidence_text"]) <= 1000 + 20  # Allow for sequence suffix

    def test_control_evidence_structure(
        self,
        exporter: AuditManagerExporter,
        sample_findings: list[dict[str, object]],
        metadata: dict[str, object],
        tmp_path: Path,
    ) -> None:
        result = exporter.export_to_file(sample_findings, metadata, tmp_path)
        json_files = [f for f in result.output_files if f.suffix == ".json"]
        data = json.loads(json_files[0].read_text())
        assert "control_evidence" in data
        entry = data["control_evidence"][0]
        assert "framework" in entry
        assert "control_id" in entry
        assert "audit_manager_control_hint" in entry
        assert "evidence_text" in entry
        assert "findings_count" in entry
        assert "severity_summary" in entry
        assert "native_ids" in entry

    def test_companion_instructions(
        self,
        exporter: AuditManagerExporter,
        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()
