"""Markdown exporter for audit history."""

from datetime import datetime
from pathlib import Path
from typing import Any

from tools.view_history.utils import format_timestamp, normalize_affected_files


class MarkdownExporter:
    """Exports audits to Markdown format."""

    SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"]

    def __init__(self, project_name: str, audits: list[dict[str, Any]]) -> None:
        self.project_name = project_name
        self.audits = sorted(
            audits, key=lambda a: a.get("timestamp", ""), reverse=True
        )

    def export(self, output_path: Path) -> None:
        """Export audits to a Markdown file."""
        content = self.to_markdown()
        output_path.write_text(content, encoding="utf-8")

    def to_markdown(self) -> str:
        """Convert audits to Markdown string."""
        total_findings = sum(
            a.get("summary", {}).get("total_findings", 0)
            or a.get("total_findings", 0)
            for a in self.audits
        )
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        md = f"# Audit Summary: {self.project_name}\n\n"
        md += f"**Generated:** {timestamp}\n"
        md += f"**Total Audits:** {len(self.audits)} | **Total Findings:** {total_findings}\n\n"
        md += "## Recent Audits\n\n"

        for audit in self.audits:
            md += self._audit_to_markdown(audit)

        return md

    def _audit_to_markdown(self, audit: dict[str, Any]) -> str:
        """Convert a single audit to Markdown."""
        lens = audit.get("lens", "unknown")
        lens_title = lens.capitalize()
        date = format_timestamp(audit.get("timestamp", ""), "date")

        summary = audit.get("summary", {})
        findings_count = summary.get("total_findings", 0) or audit.get(
            "total_findings", 0
        )
        by_severity = summary.get("by_severity", {}) or audit.get("by_severity", {})

        md = f"### {lens_title} Audit - {date}\n"

        severity_summary = []
        for sev in self.SEVERITY_ORDER:
            count = by_severity.get(sev, 0)
            if count > 0:
                severity_summary.append(f"{count} {sev}")

        severity_str = (
            f" ({', '.join(severity_summary)})" if severity_summary else ""
        )
        md += f"- **Findings:** {findings_count}{severity_str}\n\n"

        findings = audit.get("findings", [])
        if findings:
            grouped = self._group_by_severity(findings)
            for sev in self.SEVERITY_ORDER:
                sev_findings = grouped.get(sev, [])
                if sev_findings:
                    md += f"#### {sev.capitalize()} Severity\n"
                    for f in sev_findings:
                        md += self._finding_to_markdown(f)
                    md += "\n"

        md += "---\n\n"
        return md

    def _finding_to_markdown(self, finding: dict[str, Any]) -> str:
        """Convert a single finding to Markdown."""
        category = finding.get("category", "Unknown")
        description = finding.get("description", "No description")
        remediation = finding.get("remediation", "")
        affected_files = normalize_affected_files(
            finding.get("affected_files", [])
        )

        md = f"- **{category}** - {description}\n"
        if affected_files:
            files_str = ", ".join(f"`{f}`" for f in affected_files)
            md += f"  - Files: {files_str}\n"
        if remediation:
            md += f"  - Fix: {remediation}\n"

        return md

    def _group_by_severity(
        self, findings: list[dict[str, Any]]
    ) -> dict[str, list[dict[str, Any]]]:
        """Group findings by severity."""
        grouped: dict[str, list[dict[str, Any]]] = {}
        for f in findings:
            sev = f.get("severity", "info")
            if sev not in grouped:
                grouped[sev] = []
            grouped[sev].append(f)
        return grouped



