"""
Markdown reporter — human-readable markdown report output.
"""

from __future__ import annotations

from pathlib import Path

from senshi.reporters.models import ScanResult, Severity
from senshi.utils.logger import get_logger

logger = get_logger("senshi.reporters.markdown_report")


def generate_markdown_report(
    result: ScanResult, output_path: str | None = None
) -> str:
    """Generate a markdown report from scan results."""
    lines: list[str] = []

    # Header
    lines.append("# 🔒 Senshi Security Scan Report\n")
    lines.append(f"**Target:** {result.target}")
    lines.append(f"**Mode:** {result.mode.value.upper()}")
    lines.append(f"**Provider:** {result.provider} ({result.model})")
    lines.append(f"**Started:** {result.started_at}")
    lines.append(f"**Completed:** {result.completed_at}")
    lines.append("")

    # Summary
    lines.append("## Summary\n")
    lines.append(f"| Metric | Count |")
    lines.append(f"|--------|-------|")
    lines.append(f"| Total findings | {len(result.findings)} |")
    lines.append(f"| Critical | {result.critical_count} |")
    lines.append(f"| High | {result.high_count} |")
    lines.append(f"| Medium | {result.medium_count} |")
    lines.append(f"| Low | {result.low_count} |")

    if result.mode.value == "dast":
        lines.append(f"| Endpoints tested | {result.endpoints_discovered} |")
    else:
        lines.append(f"| Files analyzed | {result.files_analyzed} |")

    if result.chains:
        lines.append(f"| Exploit chains | {len(result.chains)} |")
    lines.append("")

    # Findings
    if result.findings:
        lines.append("## Findings\n")

        # Sort by severity
        sorted_findings = sorted(
            result.findings, key=lambda f: f.severity.rank, reverse=True
        )

        for i, finding in enumerate(sorted_findings, 1):
            severity_emoji = {
                Severity.CRITICAL: "🔴",
                Severity.HIGH: "🟠",
                Severity.MEDIUM: "🟡",
                Severity.LOW: "🔵",
                Severity.INFO: "⚪",
            }

            emoji = severity_emoji.get(finding.severity, "⚪")
            lines.append(
                f"### {i}. {emoji} {finding.title}\n"
            )
            lines.append(f"**Severity:** {finding.severity.value.upper()} | "
                        f"**Confidence:** {finding.confidence.value} | "
                        f"**Category:** {finding.category}")
            if finding.cvss_estimate:
                lines.append(f"**CVSS Estimate:** {finding.cvss_estimate}")
            lines.append("")

            if finding.description:
                lines.append(f"**Description:** {finding.description}\n")

            if finding.endpoint:
                lines.append(f"**Endpoint:** `{finding.method} {finding.endpoint}`")
            if finding.file_path:
                lines.append(f"**File:** `{finding.file_path}:{finding.line_number}`")
            if finding.payload:
                lines.append(f"**Payload:** `{finding.payload}`")
            if finding.evidence:
                lines.append(f"\n**Evidence:**\n```\n{finding.evidence}\n```")
            if finding.code_snippet:
                lines.append(f"\n**Code:**\n```\n{finding.code_snippet}\n```")
            if finding.remediation:
                lines.append(f"\n**Remediation:** {finding.remediation}")

            lines.append("\n---\n")

    # Chains
    if result.chains:
        lines.append("## Exploit Chains\n")
        for i, chain in enumerate(result.chains, 1):
            lines.append(f"### Chain {i}: {chain.get('name', 'Unnamed')}\n")
            lines.append(f"**Combined Severity:** {chain.get('combined_severity', 'unknown').upper()}")
            if chain.get("combined_cvss"):
                lines.append(f"**Combined CVSS:** {chain['combined_cvss']}")
            lines.append(f"\n**Impact:** {chain.get('combined_impact', '')}\n")

            steps = chain.get("steps", [])
            if steps:
                lines.append("**Steps:**")
                for j, step in enumerate(steps, 1):
                    lines.append(f"{j}. {step}")
            lines.append("")

            if chain.get("bounty_narrative"):
                lines.append(f"**Narrative:** {chain['bounty_narrative']}\n")

    # Footer
    lines.append("---")
    lines.append("*Generated by Senshi — AI-Powered Security Scanner*")

    report = "\n".join(lines)

    if output_path:
        Path(output_path).write_text(report, encoding="utf-8")
        logger.info(f"Markdown report saved to {output_path}")

    return report
