"""HTML report generator — shareable data quality report."""
from __future__ import annotations

from pathlib import Path

from goldencheck.models.finding import Finding, Severity
from goldencheck.models.profile import DatasetProfile

__all__ = ["report_html"]

_SEVERITY_COLORS = {
    Severity.ERROR: "#ff4444",
    Severity.WARNING: "#ffbb33",
    Severity.INFO: "#33b5e5",
}

_GRADE_COLORS = {
    "A": "#00ff00", "B": "#7fff00", "C": "#ffff00", "D": "#ff7f00", "F": "#ff0000",
}


def report_html(findings: list[Finding], profile: DatasetProfile, path: Path) -> None:
    """Generate a self-contained HTML report."""
    errors = sum(1 for f in findings if f.severity == Severity.ERROR)
    warnings = sum(1 for f in findings if f.severity == Severity.WARNING)

    by_col: dict[str, dict[str, int]] = {}
    for f in findings:
        if f.severity >= Severity.WARNING:
            by_col.setdefault(f.column, {"errors": 0, "warnings": 0})
            key = "errors" if f.severity == Severity.ERROR else "warnings"
            by_col[f.column][key] = by_col[f.column].get(key, 0) + 1

    grade, score = profile.health_score(findings_by_column=by_col)
    grade_color = _GRADE_COLORS.get(grade, "#888")

    # Build findings table rows
    finding_rows = []
    for f in findings:
        color = _SEVERITY_COLORS.get(f.severity, "#888")
        conf = "H" if f.confidence >= 0.8 else "M" if f.confidence >= 0.5 else "L"
        source = " [LLM]" if f.source == "llm" else ""
        samples = ", ".join(f.sample_values[:3]) if f.sample_values else ""
        finding_rows.append(
            f'<tr><td style="color:{color};font-weight:bold">{f.severity.name}</td>'
            f'<td>{f.column}</td><td>{f.check}</td>'
            f'<td>{f.message}</td><td>{f.affected_rows}</td>'
            f'<td>{conf}{source}</td><td style="color:#888">{samples}</td></tr>'
        )

    # Build column table rows
    col_rows = []
    for c in profile.columns:
        top = ", ".join(f"{v}({n})" for v, n in c.top_values[:3]) if c.top_values else ""
        col_rows.append(
            f'<tr><td><b>{c.name}</b></td><td>{c.inferred_type}</td>'
            f'<td>{c.null_pct:.1f}%</td><td>{c.unique_pct:.1f}%</td>'
            f'<td style="color:#888">{top}</td></tr>'
        )

    html = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>GoldenCheck Report — {profile.file_path}</title>
<style>
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; margin: 40px; background: #1a1a2e; color: #eee; }}
h1 {{ color: #FFD700; }}
h2 {{ color: #ccc; border-bottom: 1px solid #333; padding-bottom: 8px; }}
table {{ border-collapse: collapse; width: 100%; margin: 16px 0; }}
th {{ text-align: left; padding: 8px; border-bottom: 2px solid #444; color: #aaa; }}
td {{ padding: 6px 8px; border-bottom: 1px solid #333; }}
.badge {{ display: inline-block; padding: 4px 16px; border-radius: 6px; font-weight: bold; font-size: 1.2em; color: #000; }}
.summary {{ display: flex; gap: 32px; margin: 16px 0; }}
.stat {{ text-align: center; }}
.stat-value {{ font-size: 2em; font-weight: bold; color: #FFD700; }}
.stat-label {{ color: #888; }}
</style></head><body>
<h1>GoldenCheck Report</h1>
<p>{profile.file_path} &mdash; {profile.row_count:,} rows, {profile.column_count} columns</p>

<div class="summary">
<div class="stat"><div class="stat-value"><span class="badge" style="background:{grade_color}">{grade}</span></div><div class="stat-label">Health ({score})</div></div>
<div class="stat"><div class="stat-value" style="color:#ff4444">{errors}</div><div class="stat-label">Errors</div></div>
<div class="stat"><div class="stat-value" style="color:#ffbb33">{warnings}</div><div class="stat-label">Warnings</div></div>
<div class="stat"><div class="stat-value">{len(findings)}</div><div class="stat-label">Total Findings</div></div>
</div>

<h2>Findings</h2>
<table>
<thead><tr><th>Severity</th><th>Column</th><th>Check</th><th>Message</th><th>Rows</th><th>Conf</th><th>Samples</th></tr></thead>
<tbody>{"".join(finding_rows)}</tbody>
</table>

<h2>Column Profile</h2>
<table>
<thead><tr><th>Column</th><th>Type</th><th>Null%</th><th>Unique%</th><th>Top Values</th></tr></thead>
<tbody>{"".join(col_rows)}</tbody>
</table>

<p style="color:#666;margin-top:32px">Generated by <a href="https://github.com/benzsevern/goldencheck" style="color:#FFD700">GoldenCheck</a></p>
</body></html>"""

    Path(path).write_text(html, encoding="utf-8")
