from __future__ import annotations

from pathlib import Path

from jinja2 import Template

from aegisrt.core.result import RunReport


_HTML_TEMPLATE = Template("""\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AegisRT Report &mdash; {{ run_id }}</title>
<style>
  :root{--pass:
  *{box-sizing:border-box;margin:0;padding:0}
  body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;background:var(--bg);color:var(--text);line-height:1.6;padding:2rem}
  .container{max-width:1100px;margin:0 auto}
  header{background:linear-gradient(135deg,
  header h1{font-size:1.5rem;margin-bottom:.5rem}
  header .meta{font-size:.9rem;opacity:.85}
  .cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:1rem;margin-bottom:2rem}
  .card{background:var(--card);border:1px solid var(--border);border-radius:8px;padding:1.2rem;text-align:center}
  .card .number{font-size:2rem;font-weight:700}
  .card .label{font-size:.85rem;color:
  .card.pass .number{color:var(--pass)}
  .card.fail .number{color:var(--fail)}
  .card.critical .number{color:var(--fail)}
  .card.high .number{color:
  .card.medium .number{color:var(--warn)}
  .card.low .number{color:var(--pass)}
  table{width:100%;border-collapse:collapse;background:var(--card);border-radius:8px;overflow:hidden;margin-bottom:2rem;border:1px solid var(--border)}
  th{background:
  td{padding:.75rem 1rem;border-bottom:1px solid var(--border);font-size:.9rem}
  tr:last-child td{border-bottom:none}
  .sev{display:inline-block;padding:2px 10px;border-radius:12px;font-size:.8rem;font-weight:600;color:
  .sev.critical{background:var(--fail)}.sev.high{background:
  .status{font-weight:700}.status.pass{color:var(--pass)}.status.fail{color:var(--fail)}
  details{margin-bottom:.5rem}
  details summary{cursor:pointer;font-weight:600;padding:.3rem 0}
  details .detail-body{padding:.5rem 1rem;background:
  .remediation{background:var(--card);border:1px solid var(--border);border-radius:8px;padding:1.5rem;margin-bottom:2rem}
  .remediation h2{margin-bottom:1rem;font-size:1.1rem}
  .remediation ul{padding-left:1.5rem}
  .remediation li{margin-bottom:.5rem;font-size:.9rem}
  footer{text-align:center;color:
</style>
</head>
<body>
<div class="container">
  <header>
    <h1>AegisRT Security Test Report</h1>
    <div class="meta">
      Run ID: {{ run_id }} &bull; Timestamp: {{ timestamp }}
      {% if target_type %}&bull; Target: {{ target_type }}{% endif %}
    </div>
  </header>

  <div class="cards">
    <div class="card"><div class="number">{{ total }}</div><div class="label">Total</div></div>
    <div class="card pass"><div class="number">{{ passed }}</div><div class="label">Passed</div></div>
    <div class="card fail"><div class="number">{{ failed }}</div><div class="label">Failed</div></div>
    {% for sev in severity_order %}
    {% if severity_counts[sev] %}
    <div class="card {{ sev }}"><div class="number">{{ severity_counts[sev] }}</div><div class="label">{{ sev|upper }}</div></div>
    {% endif %}
    {% endfor %}
  </div>

  <table>
    <thead><tr><th>Probe</th><th>Case</th><th>Severity</th><th>Confidence</th><th>Score</th><th>Status</th></tr></thead>
    <tbody>
    {% for r in results %}
    <tr>
      <td>{{ r.probe_id }}</td>
      <td>{{ r.case_id[:12] }}&hellip;</td>
      <td><span class="sev {{ r.severity }}">{{ r.severity|upper }}</span></td>
      <td>{{ "%.2f"|format(r.confidence) }}</td>
      <td>{{ "%.2f"|format(r.score) }}</td>
      <td><span class="status {{ 'pass' if r.passed else 'fail' }}">{{ "PASS" if r.passed else "FAIL" }}</span></td>
    </tr>
    {% if not r.passed %}
    <tr>
      <td colspan="6">
        <details>
          <summary>Details</summary>
          <div class="detail-body">{{ r.evidence | tojson(indent=2) }}</div>
        </details>
      </td>
    </tr>
    {% endif %}
    {% endfor %}
    </tbody>
  </table>

  {% if remediation_items %}
  <div class="remediation">
    <h2>Remediation Steps</h2>
    <ul>
    {% for item in remediation_items %}
      <li><strong>{{ item.probe_id }}</strong>: {{ item.step }}</li>
    {% endfor %}
    </ul>
  </div>
  {% endif %}

  <footer>Generated by AegisRT</footer>
</div>
</body>
</html>
""")


class HtmlReportWriter:

    def write(self, report: RunReport, path: str | Path) -> Path:
        out = Path(path)
        out.parent.mkdir(parents=True, exist_ok=True)

        results_data = report.results
        total = len(results_data)
        passed = sum(1 for r in results_data if r.passed)
        failed = total - passed

        severity_counts: dict[str, int] = {}
        for r in results_data:
            sev = r.severity.lower()
            severity_counts[sev] = severity_counts.get(sev, 0) + 1

        remediation_items: list[dict[str, str]] = []
        for r in results_data:
            if not r.passed and r.remediation:
                for step in r.remediation:
                    remediation_items.append({"probe_id": r.probe_id, "step": step})

        html = _HTML_TEMPLATE.render(
            run_id=report.run_id,
            timestamp=report.timestamp,
            target_type=report.target_info.get("type", ""),
            total=total,
            passed=passed,
            failed=failed,
            severity_counts=severity_counts,
            severity_order=["critical", "high", "medium", "low"],
            results=results_data,
            remediation_items=remediation_items,
        )
        out.write_text(html, encoding="utf-8")
        return out.resolve()
