"""AWS Audit Manager text evidence exporter (Team+ tier).

Produces JSON with control evidence entries, each <=1000 chars.
"""

from __future__ import annotations

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

_MAX_EVIDENCE_LENGTH = 1000


class AuditManagerExporter(EvidenceExporter):
    """Export findings as AWS Audit Manager evidence JSON."""

    FORMAT_ID = "audit-manager"
    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"))

        output_path = output_dir / f"complyform-audit-manager-{scan_id}.json"
        instructions_path = output_dir / "audit-manager-import-instructions.md"

        # Group findings by control
        by_control: dict[str, list[dict[str, object]]] = {}
        for f in findings:
            key = f"{f.get('framework', '')}:{f.get('control_id', '')}"
            by_control.setdefault(key, []).append(f)

        control_evidence: list[dict[str, object]] = []
        for key, control_findings in sorted(by_control.items()):
            framework, control_id = key.split(":", 1)
            severity_counts: dict[str, int] = {}
            native_ids_list: list[str] = []

            for cf in control_findings:
                sev = str(cf.get("severity", "MEDIUM"))
                severity_counts[sev] = severity_counts.get(sev, 0) + 1
                nids = cf.get("native_ids")
                if isinstance(nids, dict):
                    for v in nids.values():
                        if v:
                            native_ids_list.append(str(v))

            # Build evidence text
            full_text = _build_evidence_text(control_findings, framework, control_id)

            # Split into chunks if needed
            chunks = _split_evidence(full_text, _MAX_EVIDENCE_LENGTH)
            for idx, chunk in enumerate(chunks):
                seq = f" [{idx + 1}/{len(chunks)}]" if len(chunks) > 1 else ""
                entry: dict[str, object] = {
                    "framework": framework,
                    "control_id": control_id,
                    "audit_manager_control_hint": f"{framework.upper()} {control_id}",
                    "evidence_text": chunk + seq,
                    "findings_count": len(control_findings),
                    "severity_summary": severity_counts,
                    "native_ids": native_ids_list,
                }
                control_evidence.append(entry)

        envelope = {
            "schema_version": 1,
            "tool": "complyform",
            "tool_version": __version__,
            "scan_id": scan_id,
            "control_evidence": control_evidence,
        }

        output_path.write_text(json.dumps(envelope, indent=2), encoding="utf-8")

        instructions = _AM_INSTRUCTIONS.format(
            filename=output_path.name,
            control_count=len(by_control),
        )
        instructions_path.write_text(instructions, encoding="utf-8")

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


def _build_evidence_text(
    findings: list[dict[str, object]], framework: str, control_id: str
) -> str:
    """Build evidence text from findings."""
    lines = [f"ComplyForm Assessment: {framework} {control_id}"]
    for f in findings:
        resource = str(f.get("resource_address", ""))
        status = str(f.get("status", ""))
        severity = str(f.get("severity", ""))
        finding_text = str(f.get("finding", ""))
        lines.append(f"Resource: {resource} | Status: {status} | Severity: {severity}")
        if finding_text:
            lines.append(f"  Finding: {finding_text}")
    return "\n".join(lines)


def _split_evidence(text: str, max_len: int) -> list[str]:
    """Split text into chunks of max_len characters."""
    if len(text) <= max_len:
        return [text]
    chunks: list[str] = []
    while text:
        if len(text) <= max_len:
            chunks.append(text)
            break
        # Find last newline before max_len
        split_at = text.rfind("\n", 0, max_len)
        if split_at <= 0:
            split_at = max_len
        chunks.append(text[:split_at])
        text = text[split_at:].lstrip("\n")
    return chunks


_AM_INSTRUCTIONS = """\
# AWS Audit Manager Import Instructions

## File: {filename}

Controls: {control_count}

## Import Steps

1. Open AWS Audit Manager console
2. Navigate to your assessment
3. For each control, add manual evidence
4. Use the `evidence_text` field content as "Text evidence"
5. Match controls using `audit_manager_control_hint`

## API Reference

See: https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_BatchImportEvidenceToAssessmentControl.html
"""
