"""Render verification results as self-contained HTML or SVG badge.

Pure renderers. No CLI logic. No filesystem writes.
"""
from __future__ import annotations

import html
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional

from assay.verification_status import (
    VERDICT_COLORS,
    VERDICT_LABELS,
    VerificationVerdict,
)


def render_verification_html(
    *,
    verdict: VerificationVerdict,
    pack_id: str,
    run_id: str,
    pack_dir: str,
    integrity_passed: bool,
    claim_check: str,
    receipt_count: int,
    signer_id: str,
    errors: List[Dict[str, Any]],
    warnings: List[str],
    head_hash: Optional[str] = None,
    generated_at: Optional[str] = None,
    version: Optional[str] = None,
) -> str:
    """Render a self-contained HTML verification report.

    Returns the full HTML string. Caller is responsible for writing to disk.
    """
    if generated_at is None:
        generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

    color = VERDICT_COLORS[verdict]
    label = VERDICT_LABELS[verdict]
    integrity_str = "Verified" if integrity_passed else "Compromised"
    integrity_color = "#4c1" if integrity_passed else "#e05d44"

    # Escape all user-supplied strings
    e_pack_id = html.escape(pack_id)
    e_run_id = html.escape(run_id)
    e_pack_dir = html.escape(pack_dir)
    e_signer = html.escape(signer_id)
    e_head = html.escape(head_hash[:16] + "..." if head_hash else "N/A")
    e_generated = html.escape(generated_at)
    e_version = html.escape(version or "unknown")
    e_claim_check = html.escape(claim_check)
    e_receipt_count = html.escape(str(receipt_count))

    # Error rows
    error_rows = ""
    if errors:
        error_rows = "<h3>Failure Details</h3><table><tr><th>Code</th><th>Mechanism</th><th>Message</th></tr>"
        for err in errors:
            e_code = html.escape(str(err.get("code", "")))
            e_mech = html.escape(str(err.get("failure_mechanism", "")))
            e_msg = html.escape(str(err.get("message", "")))
            error_rows += f"<tr><td><code>{e_code}</code></td><td>{e_mech}</td><td>{e_msg}</td></tr>"
        error_rows += "</table>"

    # Warning rows
    warning_rows = ""
    if warnings:
        warning_rows = "<h3>Warnings</h3><ul>"
        for w in warnings:
            warning_rows += f"<li>{html.escape(w)}</li>"
        warning_rows += "</ul>"

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Assay Verification Report — {e_pack_id}</title>
<style>
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}
  body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; max-width: 720px; margin: 2rem auto; padding: 0 1rem; color: #24292f; background: #fff; }}
  h1 {{ font-size: 1.4rem; margin-bottom: 0.5rem; }}
  h3 {{ font-size: 1rem; margin: 1.5rem 0 0.5rem; }}
  .verdict {{ display: inline-block; padding: 0.4rem 1rem; border-radius: 4px; color: #fff; font-weight: 700; font-size: 1.1rem; }}
  .subtitle {{ color: #57606a; margin: 0.25rem 0 1.5rem; }}
  table {{ width: 100%; border-collapse: collapse; margin-bottom: 1rem; }}
  th, td {{ text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid #d0d7de; }}
  th {{ font-weight: 600; background: #f6f8fa; }}
  code {{ background: #f6f8fa; padding: 0.15rem 0.4rem; border-radius: 3px; font-size: 0.9em; }}
  pre {{ background: #f6f8fa; padding: 0.8rem; border-radius: 4px; overflow-x: auto; font-size: 0.85rem; }}
  .footer {{ margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #d0d7de; color: #57606a; font-size: 0.8rem; }}
</style>
</head>
<body>
<h1>Assay Verification Report</h1>
<div><span class="verdict" style="background:{color}">{html.escape(verdict)}</span></div>
<p class="subtitle">{html.escape(label)}</p>

<h3>Trust Summary</h3>
<table>
<tr><th>Field</th><th>Value</th></tr>
<tr><td>Integrity</td><td><span style="color:{integrity_color};font-weight:600">{integrity_str}</span></td></tr>
<tr><td>Claims</td><td>{e_claim_check}</td></tr>
<tr><td>Classification</td><td><strong>{html.escape(verdict)}</strong></td></tr>
<tr><td>Signer</td><td><code>{e_signer}</code></td></tr>
</table>

<h3>Pack Identity</h3>
<table>
<tr><th>Field</th><th>Value</th></tr>
<tr><td>Pack ID</td><td><code>{e_pack_id}</code></td></tr>
<tr><td>Run ID</td><td><code>{e_run_id}</code></td></tr>
<tr><td>Receipts</td><td>{e_receipt_count}</td></tr>
<tr><td>Head Hash</td><td><code>{e_head}</code></td></tr>
<tr><td>Verified At</td><td>{e_generated}</td></tr>
</table>

{error_rows}
{warning_rows}

<h3>Reproduce</h3>
<pre>assay verify-pack {e_pack_dir}</pre>

<div class="footer">
Generated by Assay v{e_version} &middot; {e_generated}
</div>
</body>
</html>"""


def render_verification_badge(verdict: VerificationVerdict) -> str:
    """Render a static SVG badge for the given verdict.

    Returns SVG string. No external fonts, no remote assets, deterministic output.
    """
    color = VERDICT_COLORS[verdict]
    label = "assay"
    value = verdict

    # Compute widths: ~6.5px per character at 11px font, plus padding
    label_width = len(label) * 6.5 + 10
    value_width = len(value) * 6.5 + 10
    total_width = label_width + value_width
    label_x = label_width / 2
    value_x = label_width + value_width / 2

    return f"""<svg xmlns="http://www.w3.org/2000/svg" width="{total_width:.0f}" height="20">
  <linearGradient id="s" x2="0" y2="100%">
    <stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
    <stop offset="1" stop-opacity=".1"/>
  </linearGradient>
  <clipPath id="r"><rect width="{total_width:.0f}" height="20" rx="3" fill="#fff"/></clipPath>
  <g clip-path="url(#r)">
    <rect width="{label_width:.0f}" height="20" fill="#555"/>
    <rect x="{label_width:.0f}" width="{value_width:.0f}" height="20" fill="{color}"/>
    <rect width="{total_width:.0f}" height="20" fill="url(#s)"/>
  </g>
  <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
    <text x="{label_x:.0f}" y="15" fill="#010101" fill-opacity=".3">{html.escape(label)}</text>
    <text x="{label_x:.0f}" y="14">{html.escape(label)}</text>
    <text x="{value_x:.0f}" y="15" fill="#010101" fill-opacity=".3">{html.escape(value)}</text>
    <text x="{value_x:.0f}" y="14">{html.escape(value)}</text>
  </g>
</svg>"""
