"""Microsoft Purview compliance exporter (Team+ tier).

Produces CSV for improvement action mapping and JSON for structured evidence.
"""

from __future__ import annotations

import csv
import io
import json
from typing import TYPE_CHECKING

from complyform import __version__
from complyform.core.generators.evidence_export.base import (
    EvidenceExporter,
    ExportResult,
)

if TYPE_CHECKING:
    from pathlib import Path


class PurviewExporter(EvidenceExporter):
    """Export findings as Purview CSV + evidence JSON."""

    FORMAT_ID = "purview"
    TIER_FEATURE = "evidence_export_native"

    def export_to_file(
        self,
        findings: list[dict[str, object]],
        metadata: dict[str, object],
        output_dir: Path,
        project_label: str | None = None,
    ) -> ExportResult:
        output_dir.mkdir(parents=True, exist_ok=True)
        scan_id = str(metadata.get("scan_id", "unknown"))
        timestamp = str(metadata.get("timestamp", ""))

        csv_path = output_dir / f"complyform-purview-{scan_id}.csv"
        evidence_path = output_dir / f"complyform-purview-evidence-{scan_id}.json"
        instructions_path = output_dir / "purview-import-instructions.md"

        # Build CSV
        csv_buffer = io.StringIO()
        writer = csv.writer(csv_buffer)
        writer.writerow(
            [
                "improvement_action_title",
                "implementation_status",
                "test_status",
                "test_date",
                "notes",
                "evidence_file",
            ]
        )

        evidence_records: list[dict[str, object]] = []

        for finding in findings:
            control_id = str(finding.get("control_id", ""))
            framework = str(finding.get("framework", ""))
            status = str(finding.get("status", "FAIL"))
            resource_address = str(finding.get("resource_address", ""))

            impl_status = "implemented" if status == "PASS" else "not_implemented"
            test_status = "passed" if status == "PASS" else "failed"
            title = f"{framework} {control_id}: {resource_address}"

            writer.writerow(
                [
                    title,
                    impl_status,
                    test_status,
                    timestamp,
                    str(finding.get("finding", "")),
                    evidence_path.name,
                ]
            )

            evidence_records.append(
                {
                    "control_id": control_id,
                    "framework": framework,
                    "resource_address": resource_address,
                    "status": status,
                    "severity": str(finding.get("severity", "")),
                    "finding": str(finding.get("finding", "")),
                    "remediation": str(finding.get("remediation", "")),
                }
            )

        csv_path.write_text(csv_buffer.getvalue(), encoding="utf-8")

        evidence_envelope = {
            "schema_version": 1,
            "tool": "complyform",
            "tool_version": __version__,
            "scan_id": scan_id,
            "evidence": evidence_records,
        }
        evidence_path.write_text(
            json.dumps(evidence_envelope, indent=2), encoding="utf-8"
        )

        instructions = _PURVIEW_INSTRUCTIONS.format(
            csv_filename=csv_path.name,
            evidence_filename=evidence_path.name,
            record_count=len(findings),
        )
        instructions_path.write_text(instructions, encoding="utf-8")

        return ExportResult(
            format=self.FORMAT_ID,
            output_files=[csv_path, evidence_path, instructions_path],
            record_count=len(findings),
        )


_PURVIEW_INSTRUCTIONS = """\
# Microsoft Purview Import Instructions

## Files

- CSV: {csv_filename}
- Evidence JSON: {evidence_filename}
- Records: {record_count}

## Import Steps

1. Open Microsoft Purview Compliance Portal
2. Navigate to Compliance Manager > Assessments
3. Import improvement actions from the CSV file
4. Attach evidence JSON as supporting documentation

## Status Values

- `implemented` / `not_implemented` for implementation status
- `passed` / `failed` for test status
"""
