"""SCC v2 custom finding NDJSON exporter (Team+ tier).

Produces one JSON object per line for Google Security Command Center import.
"""

from __future__ import annotations

import hashlib
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 SccJsonExporter(EvidenceExporter):
    """Export findings as SCC v2 NDJSON."""

    FORMAT_ID = "scc-json"
    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", ""))

        ndjson_path = output_dir / f"complyform-scc-findings-{scan_id}.ndjson"
        instructions_path = output_dir / "scc-import-instructions.md"

        records: list[str] = []
        for finding in findings:
            resource_address = str(finding.get("resource_address", ""))
            resource_hash = hashlib.sha256(resource_address.encode()).hexdigest()[:8]
            control_id = str(finding.get("control_id", ""))
            framework = str(finding.get("framework", ""))
            status = str(finding.get("status", "FAIL"))
            severity = str(finding.get("severity", "MEDIUM"))

            state = "ACTIVE" if status == "FAIL" else "INACTIVE"
            checkov_id = finding.get("checkov_id") or ""
            native_ids = finding.get("native_ids") or {}
            scc_detector = ""
            if isinstance(native_ids, dict):
                scc_detector = str(native_ids.get("scc", ""))

            cross_mappings = finding.get("cross_mappings")
            cross_mappings_str = json.dumps(cross_mappings) if cross_mappings else "[]"

            record = {
                "findingId": f"cf-{control_id}-{resource_hash}",
                "finding": {
                    "state": state,
                    "severity": severity,
                    "findingClass": "MISCONFIGURATION",
                    "category": f"COMPLYFORM_{control_id}",
                    "resourceName": resource_address,
                    "eventTime": timestamp,
                    "sourceProperties": {
                        "complyform_control_id": control_id,
                        "complyform_framework": framework,
                        "complyform_resource_address": resource_address,
                        "complyform_resource_type": str(
                            finding.get("resource_type", "")
                        ),
                        "complyform_severity": severity,
                        "complyform_status": status,
                        "complyform_finding": str(finding.get("finding", "")),
                        "complyform_remediation": str(finding.get("remediation", "")),
                        "complyform_scan_id": scan_id,
                        "complyform_scan_timestamp": timestamp,
                        "complyform_version": __version__,
                        "complyform_checkov_id": str(checkov_id),
                        "complyform_scc_detector": scc_detector,
                        "complyform_cross_mappings": cross_mappings_str,
                    },
                    "externalUri": f"https://complyform.dev/docs/controls/{framework}/{control_id}",
                },
            }
            records.append(json.dumps(record, separators=(",", ":")))

        ndjson_path.write_text(
            "\n".join(records) + ("\n" if records else ""),
            encoding="utf-8",
        )

        # Write companion instructions
        instructions = _SCC_INSTRUCTIONS.format(
            filename=ndjson_path.name,
            record_count=len(records),
        )
        instructions_path.write_text(instructions, encoding="utf-8")

        return ExportResult(
            format=self.FORMAT_ID,
            output_files=[ndjson_path, instructions_path],
            record_count=len(records),
        )


_SCC_INSTRUCTIONS = """\
# SCC Import Instructions

## File: {filename}

Records: {record_count}

## Import Steps

1. Navigate to Google Cloud Console > Security Command Center
2. Use the SCC API `organizations.sources.findings.create` endpoint
3. Each line in the NDJSON file is a separate finding record
4. Parse each line as JSON and submit via the API

## API Reference

See: https://cloud.google.com/security-command-center/docs/reference/rest/v2/organizations.sources.findings/create
"""
