"""Report generation for compliance test results."""

from __future__ import annotations

import json
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ai4gh.compliance.runner import SuiteResult


def to_json(result: SuiteResult) -> str:
    """Generate JSON report from suite result."""
    data = {
        "spec": result.spec,
        "base_url": result.base_url,
        "summary": {
            "total": result.total,
            "passed": result.passed,
            "failed": result.failed,
            "skipped": result.skipped,
            "errors": result.errors,
            "success_rate": round(result.success_rate, 1),
            "duration_ms": round(result.duration_ms, 1),
        },
        "tests": [
            {
                "name": r.name,
                "status": r.status.value,
                "message": r.message,
                "duration_ms": round(r.duration_ms, 1),
                "endpoint": r.endpoint,
            }
            for r in result.results
        ],
    }
    return json.dumps(data, indent=2)


def to_junit_xml(result: SuiteResult) -> str:
    """Generate JUnit XML report from suite result."""
    lines = [
        '<?xml version="1.0" encoding="UTF-8"?>',
        f'<testsuite name="{result.spec}" tests="{result.total}" '
        f'failures="{result.failed}" errors="{result.errors}" '
        f'skipped="{result.skipped}" '
        f'time="{result.duration_ms / 1000:.3f}">',
    ]
    for r in result.results:
        time_s = r.duration_ms / 1000
        lines.append(f'  <testcase name="{r.name}" classname="{result.spec}" time="{time_s:.3f}">')
        if r.status.value == "fail":
            msg = _escape_xml(r.message)
            lines.append(f'    <failure message="{msg}"/>')
        elif r.status.value == "error":
            msg = _escape_xml(r.message)
            lines.append(f'    <error message="{msg}"/>')
        elif r.status.value == "skip":
            msg = _escape_xml(r.message)
            lines.append(f'    <skipped message="{msg}"/>')
        lines.append("  </testcase>")
    lines.append("</testsuite>")
    return "\n".join(lines)


def to_html(result: SuiteResult) -> str:
    """Generate HTML report from suite result."""
    rows = ""
    for r in result.results:
        status_class = {
            "pass": "pass",
            "fail": "fail",
            "skip": "skip",
            "error": "error",
        }.get(r.status.value, "")
        msg = _escape_html(r.message) if r.message else ""
        rows += (
            f"<tr class='{status_class}'>"
            f"<td>{_escape_html(r.name)}</td>"
            f"<td>{r.status.value}</td>"
            f"<td>{msg}</td>"
            f"<td>{r.duration_ms:.1f}ms</td>"
            f"</tr>\n"
        )

    return f"""<!DOCTYPE html>
<html>
<head>
<title>GA4GH Compliance: {_escape_html(result.spec)}</title>
<style>
body {{ font-family: sans-serif; margin: 2em; }}
table {{ border-collapse: collapse; width: 100%; }}
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
th {{ background: #f5f5f5; }}
.pass {{ background: #e8f5e9; }}
.fail {{ background: #ffebee; }}
.skip {{ background: #fff3e0; }}
.error {{ background: #fce4ec; }}
.summary {{ margin: 1em 0; }}
</style>
</head>
<body>
<h1>GA4GH Compliance Report: {_escape_html(result.spec)}</h1>
<p>Server: {_escape_html(result.base_url)}</p>
<div class="summary">
<p>Total: {result.total} | Passed: {result.passed} | Failed: {result.failed} |
Skipped: {result.skipped} | Errors: {result.errors} |
Success Rate: {result.success_rate:.1f}% |
Duration: {result.duration_ms:.1f}ms</p>
</div>
<table>
<thead><tr><th>Test</th><th>Status</th><th>Message</th><th>Duration</th></tr></thead>
<tbody>
{rows}</tbody>
</table>
</body>
</html>"""


def _escape_xml(text: str) -> str:
    """Escape special XML characters."""
    return (
        text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
    )


def _escape_html(text: str) -> str:
    """Escape special HTML characters."""
    return _escape_xml(text)
