"""Export HTML translation report."""

from __future__ import annotations

from datetime import datetime
from pathlib import Path
from typing import Optional


def generate_report(
    file_name: str,
    total: int,
    translated: int,
    fuzzy: int,
    untranslated: int,
    quality_score: float,
    lint_issues: list[dict],
    glossary_violations: list[dict],
    output_path: Optional[str | Path] = None,
) -> str:
    """Generate an HTML translation status report. Returns the HTML string."""
    pct = round(translated / total * 100, 1) if total else 100.0
    fuzzy_pct = round(fuzzy / total * 100, 1) if total else 0.0
    untrans_pct = round(untranslated / total * 100, 1) if total else 0.0

    issues_html = ""
    if lint_issues:
        rows = ""
        for issue in lint_issues[:100]:
            sev = issue.get("severity", "info")
            color = {"error": "#dc3545", "warning": "#ffc107"}.get(sev, "#17a2b8")
            rows += f"""<tr>
                <td style="color:{color};font-weight:bold">{sev.upper()}</td>
                <td>#{issue.get('entry_index', '?')}</td>
                <td>{_esc(issue.get('message', ''))}</td>
                <td>{_esc(issue.get('msgid', '')[:60])}</td>
            </tr>"""
        issues_html = f"""
        <h2>Lint Issues ({len(lint_issues)})</h2>
        <table>
            <tr><th>Severity</th><th>Entry</th><th>Message</th><th>Source</th></tr>
            {rows}
        </table>"""

    glossary_html = ""
    if glossary_violations:
        rows = ""
        for v in glossary_violations[:50]:
            rows += f"""<tr>
                <td>#{v.get('entry_index', '?')}</td>
                <td>{_esc(v.get('message', ''))}</td>
            </tr>"""
        glossary_html = f"""
        <h2>Glossary Violations ({len(glossary_violations)})</h2>
        <table>
            <tr><th>Entry</th><th>Message</th></tr>
            {rows}
        </table>"""

    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Translation Report — {_esc(file_name)}</title>
<style>
    body {{ font-family: -apple-system, sans-serif; max-width: 900px; margin: 2em auto; padding: 0 1em; }}
    h1 {{ color: #333; }}
    .stats {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1em; margin: 1.5em 0; }}
    .stat {{ background: #f8f9fa; border-radius: 8px; padding: 1em; text-align: center; }}
    .stat .value {{ font-size: 2em; font-weight: bold; }}
    .stat .label {{ color: #666; font-size: 0.9em; }}
    .progress {{ background: #e9ecef; border-radius: 8px; height: 24px; margin: 1em 0; overflow: hidden; }}
    .progress-bar {{ height: 100%; border-radius: 8px; transition: width 0.3s; }}
    .bg-success {{ background: #28a745; }}
    .bg-warning {{ background: #ffc107; }}
    .bg-danger {{ background: #dc3545; }}
    table {{ width: 100%; border-collapse: collapse; margin: 1em 0; }}
    th, td {{ border: 1px solid #dee2e6; padding: 0.5em; text-align: left; }}
    th {{ background: #f8f9fa; }}
    .score {{ font-size: 3em; font-weight: bold; color: {'#28a745' if quality_score >= 80 else '#ffc107' if quality_score >= 50 else '#dc3545'}; }}
    footer {{ color: #999; font-size: 0.8em; margin-top: 3em; }}
</style>
</head>
<body>
<h1>📊 Translation Report</h1>
<p><strong>File:</strong> {_esc(file_name)}<br>
<strong>Generated:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M')}</p>

<div class="stats">
    <div class="stat"><div class="value">{total}</div><div class="label">Total strings</div></div>
    <div class="stat"><div class="value" style="color:#28a745">{translated}</div><div class="label">Translated</div></div>
    <div class="stat"><div class="value" style="color:#ffc107">{fuzzy}</div><div class="label">Fuzzy</div></div>
    <div class="stat"><div class="value" style="color:#dc3545">{untranslated}</div><div class="label">Untranslated</div></div>
</div>

<h2>Progress</h2>
<div class="progress">
    <div class="progress-bar bg-success" style="width:{pct}%;display:inline-block"></div><div class="progress-bar bg-warning" style="width:{fuzzy_pct}%;display:inline-block"></div><div class="progress-bar bg-danger" style="width:{untrans_pct}%;display:inline-block"></div>
</div>
<p>{pct}% translated, {fuzzy_pct}% fuzzy, {untrans_pct}% untranslated</p>

<h2>Quality Score</h2>
<p class="score">{quality_score:.0f}%</p>

{issues_html}
{glossary_html}

<footer>Generated by LinguaEdit</footer>
</body>
</html>"""

    if output_path:
        Path(output_path).write_text(html, "utf-8")

    return html


def _esc(s: str) -> str:
    """HTML escape."""
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
