"""Generate HTML report."""

from __future__ import annotations

from pathlib import Path

import pandas as pd
from jinja2 import Template

REPORT_TEMPLATE = Template(
    """
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>BABAPPA report</title>
    <style>
      body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; margin: 2rem; }
      h1, h2 { color: #1f3b5f; }
      table { border-collapse: collapse; width: 100%; margin-bottom: 1.2rem; }
      th, td { border: 1px solid #ddd; padding: 0.45rem; text-align: left; font-size: 0.92rem; }
      th { background: #f3f6fa; }
      .warn { color: #9f6000; }
      .caution { background: #fff8e5; border-left: 4px solid #e0a800; padding: 0.8rem; }
      .ok { color: #2e7d32; }
      .plot { max-width: 720px; border: 1px solid #ddd; margin-bottom: 1rem; }
      code { background: #f7f7f7; padding: 0.1rem 0.25rem; }
    </style>
  </head>
  <body>
    <h1>BABAPPA Analysis Report</h1>

    <p>
      BABAPPA tests whether observed gene-level dispersion exceeds expectation under a configured neutral model.
      This is a complementary gene-level deviation test, not a direct replacement for codeml/HyPhy site/branch inference.
    </p>

    <div class="caution">
      <strong>Interpretation caution:</strong>
      Significant results can reflect weak distributed adaptation, relaxation of constraint, compositional effects,
      alignment issues, tree misspecification, or other null-model deviations.
    </div>

    <h2>Technical Summary</h2>
    <p><strong>Run manifest:</strong> <code>{{ manifest_path }}</code></p>
    <p><strong>Null model:</strong> {{ null_model_desc }}</p>
    <p><strong>Smoothing bandwidth:</strong> {{ smoothing_bandwidth }}</p>

    <h2>Gene Results</h2>
    {{ scores_table | safe }}

    <h2>Warning Flags</h2>
    {% if warnings %}
    <ul>
      {% for line in warnings %}
      <li class="warn">{{ line }}</li>
      {% endfor %}
    </ul>
    {% else %}
    <p class="ok">No warning flags in summary table.</p>
    {% endif %}

    {% if plots.null_distribution %}
      <h2>Null Distribution</h2>
      <img class="plot" src="{{ plots.null_distribution }}" alt="null distribution">
    {% endif %}

    {% if plots.site_contribution %}
      <h2>Site Contributions</h2>
      <img class="plot" src="{{ plots.site_contribution }}" alt="site contributions">
    {% endif %}

    {% if plots.sensitivity %}
      <h2>Sensitivity Analysis</h2>
      <img class="plot" src="{{ plots.sensitivity }}" alt="sensitivity">
    {% endif %}

    <h2>Plain-Language Interpretation</h2>
    <p>
      A significant gene means: “Observed dispersion exceeds null expectation under the configured neutral model.”
      Follow-up analyses (site/branch specific methods) are recommended before mechanistic interpretation.
    </p>
  </body>
</html>
"""
)


def build_report(
    scores: pd.DataFrame,
    outpath: str | Path,
    manifest_path: str,
    null_model_desc: str,
    smoothing_bandwidth: float,
    warnings: list[str],
    plots: dict[str, str],
) -> Path:
    html = REPORT_TEMPLATE.render(
        scores_table=scores.to_html(index=False, classes="scores", border=0),
        manifest_path=manifest_path,
        null_model_desc=null_model_desc,
        smoothing_bandwidth=f"{smoothing_bandwidth:.4f}",
        warnings=warnings,
        plots=plots,
    )
    out = Path(outpath)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(html, encoding="utf-8")
    return out
