"""Compliance-specific Markdown report generator."""

from __future__ import annotations

from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from cloud_audit.compliance.engine import ComplianceReport


def generate_compliance_markdown(report: ComplianceReport) -> str:
    """Generate a Markdown compliance report."""
    cr = report
    scan = cr.scan_report
    now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    score = cr.readiness_score

    lines: list[str] = []
    lines.append(f"# {cr.framework_name} v{cr.version} - Compliance Report")
    lines.append("")
    lines.append(
        f"**Readiness Score: {score:.0f}%** ({cr.controls_passing}/{cr.controls_assessed} assessed controls passing)"
    )
    lines.append("")
    lines.append("| Metric | Value |")
    lines.append("|--------|-------|")
    lines.append(f"| Account | {scan.account_id} |")
    lines.append(f"| Regions | {', '.join(scan.regions)} |")
    lines.append(f"| Scanned | {now} |")
    lines.append(f"| Controls total | {len(cr.controls)} |")
    lines.append(f"| Passing | {cr.controls_passing} |")
    lines.append(f"| Failing | {cr.controls_failing} |")
    lines.append(f"| Partial | {cr.controls_partial} |")
    lines.append(f"| Manual review | {cr.controls_not_assessed} |")
    lines.append("")

    if cr.disclaimer:
        lines.append(f"> {cr.disclaimer}")
        lines.append("")

    # Attack chain violations
    if cr.chain_violations:
        lines.append("## Attack Chain Violations")
        lines.append("")
        for chain, violated_controls in cr.chain_violations:
            ctrl_ids = ", ".join(violated_controls)
            lines.append(f"**{chain.severity.value.upper()}** - {chain.name}")
            lines.append(f"- {chain.attack_narrative}")
            lines.append(f"- Priority fix: {chain.priority_fix}")
            lines.append(f"- Violates controls: {ctrl_ids}")
            lines.append("")

    # Group controls by section
    sections: dict[str, list[Any]] = {}
    for ctrl in cr.controls:
        sec = ctrl.section or "Other"
        sections.setdefault(sec, []).append(ctrl)

    for section_name, ctrls in sections.items():
        section_pass = sum(1 for c in ctrls if c.status == "PASS")
        lines.append(f"## {section_name} ({section_pass}/{len(ctrls)} passing)")
        lines.append("")
        lines.append("| Status | ID | Title | Level | Checks |")
        lines.append("|--------|----|-------|-------|--------|")

        for ctrl in ctrls:
            status_emoji = {"PASS": "PASS", "FAIL": "**FAIL**", "PARTIAL": "PARTIAL", "NOT_ASSESSED": "N/A"}[
                ctrl.status
            ]
            chain_mark = " !" if ctrl.violated_by_chains else ""
            checks_str = f"{ctrl.checks_passed}/{ctrl.checks_total}" if ctrl.checks_total > 0 else "-"
            title = _md_escape(ctrl.title[:55])
            lines.append(f"| {status_emoji}{chain_mark} | {ctrl.control_id} | {title} | {ctrl.level} | {checks_str} |")

        lines.append("")

        # Failing controls detail
        failing = [c for c in ctrls if c.status in ("FAIL", "PARTIAL")]
        if failing:
            for ctrl in failing:
                lines.append(f"### {ctrl.control_id} - {ctrl.title}")
                lines.append("")
                lines.append(f"*{ctrl.evidence_statement}*")
                lines.append("")

                if ctrl.violated_by_chains:
                    chain_ids = ", ".join(ctrl.violated_by_chains)
                    lines.append(f"> Attack chain violation: {chain_ids}")
                    lines.append("")

                for finding in ctrl.findings:
                    lines.append(f"**{finding.severity.value.upper()}** `{finding.check_id}` - {finding.title}")
                    lines.append(f"- Resource: `{finding.resource_id}`")

                    if finding.remediation:
                        rem = finding.remediation
                        if rem.cli:
                            lines.append(f"- CLI: `{rem.cli.split(chr(10))[0]}`")
                        if rem.doc_url:
                            lines.append(f"- [Documentation]({rem.doc_url})")

                    lines.append("")

    lines.append("---")
    lines.append(f"*Generated by [cloud-audit](https://github.com/gebalamariusz/cloud-audit) - {now}*")

    return "\n".join(lines)


def _md_escape(text: str) -> str:
    """Escape Markdown special characters."""
    return text.replace("|", "\\|").replace("\n", " ").replace("`", "\\`").replace("*", "\\*")
