"""Markdown reporter for @khaostest results.

Generates Markdown suitable for GitHub Step Summaries ($GITHUB_STEP_SUMMARY),
GitLab job logs, and PR comments.
"""

from __future__ import annotations

from datetime import datetime
from pathlib import Path

from khaos.testing.runner import TestSummary


class TestMarkdownReporter:
    """Generate Markdown report from @khaostest TestSummary.

    Sections: verdict banner, summary line, results table, failure details.
    """

    def __init__(self, summary: TestSummary) -> None:
        self.summary = summary

    def generate(self) -> str:
        """Generate Markdown report string."""
        lines: list[str] = []

        # Header
        lines.append("# Khaos Agent Test Results")
        lines.append("")

        # Verdict banner
        if self.summary.failed == 0:
            lines.append("> :white_check_mark: **All tests passed**")
        else:
            lines.append(f"> :x: **{self.summary.failed} test(s) failed**")
        lines.append("")

        # Summary line
        duration = self.summary.duration_ms
        if duration >= 1000:
            time_str = f"{duration / 1000:.1f}s"
        else:
            time_str = f"{duration:.0f}ms"

        lines.append(
            f"**{self.summary.total}** tests | "
            f"**{self.summary.passed}** passed | "
            f"**{self.summary.failed}** failed | "
            f"{time_str}"
        )
        lines.append("")

        # Results table
        lines.append("## Results")
        lines.append("")
        lines.append("| Status | Test | Agent | Time |")
        lines.append("|--------|------|-------|------|")

        for r in self.summary.results:
            status = ":white_check_mark:" if r.passed else ":x:"
            agent = r.agent or "-"
            dur = f"{r.duration_ms:.0f}ms"
            lines.append(f"| {status} | `{r.name}` | {agent} | {dur} |")

        lines.append("")

        # Failure details
        failures = [r for r in self.summary.results if not r.passed]
        if failures:
            lines.append("## Failures")
            lines.append("")

            for r in failures:
                lines.append(f"### `{r.name}`")
                lines.append("")
                if r.error:
                    lines.append(f"**Error:** {r.error}")
                    lines.append("")
                if r.traceback:
                    lines.append("```")
                    lines.append(r.traceback.strip())
                    lines.append("```")
                    lines.append("")

        # Footer
        lines.append("---")
        lines.append(f"*Generated by Khaos SDK at {datetime.utcnow().isoformat()}Z*")

        return "\n".join(lines)

    def write(self, path: Path) -> None:
        """Write Markdown to file."""
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(self.generate())
