"""Report generation for quality framework outputs."""
from __future__ import annotations

import csv
from datetime import UTC, datetime
import html
import json
from io import StringIO
from pathlib import Path
from typing import Any


def _badge_class(value: Any) -> str:
    if isinstance(value, bool):
        return "pass" if value else "fail"
    return "neutral"


def _render_value(value: Any) -> str:
    if isinstance(value, (dict, list)):
        return f"<pre>{html.escape(json.dumps(value, indent=2, ensure_ascii=False))}</pre>"
    return html.escape(str(value))


def generate_quality_report_html(
    *,
    title: str,
    summary: dict[str, Any],
    sections: list[dict[str, Any]],
) -> str:
    """Generate a standalone HTML report."""
    generated_at = datetime.now(UTC).isoformat()
    summary_cards = "".join(
        f'<div class="card"><span>{html.escape(str(key))}</span><strong>{html.escape(str(value))}</strong></div>'
        for key, value in summary.items()
    )
    section_html = []
    for section in sections:
        rows = section.get("rows", [])
        headers = section.get("columns", [])
        table_head = "".join(f"<th>{html.escape(str(column))}</th>" for column in headers)
        table_rows = []
        for row in rows:
            cells = []
            for column in headers:
                value = row.get(column, "")
                css = _badge_class(value) if column in {"passed", "status"} else ""
                class_attr = f' class="{css}"' if css else ""
                cells.append(f"<td{class_attr}>{_render_value(value)}</td>")
            table_rows.append("<tr>" + "".join(cells) + "</tr>")
        section_html.append(
            f"""
            <section class="panel">
              <div class="panel-header">
                <h2>{html.escape(str(section.get("title", "Section")))}</h2>
                <span>{len(rows)} rows</span>
              </div>
              <table>
                <thead><tr>{table_head}</tr></thead>
                <tbody>{''.join(table_rows)}</tbody>
              </table>
            </section>
            """
        )
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>{html.escape(title)}</title>
  <style>
    :root {{
      --bg: #0b1220;
      --panel: #111a2e;
      --line: rgba(148, 163, 184, 0.2);
      --text: #e2e8f0;
      --muted: #94a3b8;
      --pass: #14532d;
      --fail: #7f1d1d;
      --neutral: #1e293b;
      --accent: #0f766e;
    }}
    * {{ box-sizing: border-box; }}
    body {{ margin: 0; font-family: Inter, ui-sans-serif, sans-serif; background: linear-gradient(180deg, #08111d, var(--bg)); color: var(--text); }}
    .wrap {{ max-width: 1200px; margin: 0 auto; padding: 32px 20px 64px; }}
    .hero {{ display: flex; justify-content: space-between; gap: 20px; align-items: end; margin-bottom: 24px; }}
    .hero h1 {{ margin: 0 0 8px; font-size: 34px; }}
    .hero p {{ margin: 0; color: var(--muted); }}
    .summary {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 14px; margin-bottom: 24px; }}
    .card, .panel {{ background: rgba(17, 26, 46, 0.92); border: 1px solid var(--line); border-radius: 18px; }}
    .card {{ padding: 18px; display: grid; gap: 8px; }}
    .card span {{ color: var(--muted); text-transform: uppercase; font-size: 12px; letter-spacing: 0.08em; }}
    .card strong {{ font-size: 28px; }}
    .panel {{ overflow: hidden; margin-bottom: 18px; }}
    .panel-header {{ display: flex; justify-content: space-between; gap: 12px; padding: 18px 20px; border-bottom: 1px solid var(--line); }}
    table {{ width: 100%; border-collapse: collapse; }}
    th, td {{ text-align: left; padding: 14px 20px; border-top: 1px solid rgba(148,163,184,0.08); vertical-align: top; }}
    th {{ color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; border-top: none; }}
    td.pass {{ color: #bbf7d0; background: rgba(20, 83, 45, 0.4); }}
    td.fail {{ color: #fecaca; background: rgba(127, 29, 29, 0.35); }}
    td.neutral {{ background: rgba(30, 41, 59, 0.4); }}
    pre {{ margin: 0; white-space: pre-wrap; word-break: break-word; color: var(--text); }}
    .footer {{ margin-top: 20px; color: var(--muted); font-size: 13px; }}
  </style>
</head>
<body>
  <div class="wrap">
    <header class="hero">
      <div>
        <h1>{html.escape(title)}</h1>
        <p>Generated at {html.escape(generated_at)}</p>
      </div>
      <div><p>Quality framework report</p></div>
    </header>
    <section class="summary">{summary_cards}</section>
    {''.join(section_html)}
    <div class="footer">Logos ADK Quality Report</div>
  </div>
</body>
</html>"""


def write_quality_report(
    path: str | Path,
    *,
    title: str,
    summary: dict[str, Any],
    sections: list[dict[str, Any]],
) -> Path:
    """Write an HTML quality report to disk."""
    output = Path(path)
    output.write_text(
        generate_quality_report_html(title=title, summary=summary, sections=sections),
        encoding="utf-8",
    )
    return output


def generate_quality_report_markdown(
    *,
    title: str,
    summary: dict[str, Any],
    sections: list[dict[str, Any]],
) -> str:
    """Generate a markdown quality report."""
    lines = [f"# {title}", "", "## Summary", ""]
    for key, value in summary.items():
        lines.append(f"- **{key}**: {value}")
    for section in sections:
        lines.extend(["", f"## {section.get('title', 'Section')}", ""])
        columns = section.get("columns", [])
        rows = section.get("rows", [])
        if not columns:
            continue
        lines.append("| " + " | ".join(columns) + " |")
        lines.append("| " + " | ".join(["---"] * len(columns)) + " |")
        for row in rows:
            lines.append(
                "| " + " | ".join(str(row.get(column, "")).replace("\n", "<br>") for column in columns) + " |"
            )
    return "\n".join(lines) + "\n"


def generate_quality_report_csv(
    *,
    sections: list[dict[str, Any]],
) -> str:
    """Generate CSV report content across sections."""
    buffer = StringIO()
    writer = csv.writer(buffer)
    writer.writerow(["section", "column", "value", "row_index"])
    for section in sections:
        section_name = str(section.get("title", "Section"))
        for index, row in enumerate(section.get("rows", [])):
            for key, value in row.items():
                if isinstance(value, (dict, list)):
                    value = json.dumps(value, ensure_ascii=False)
                writer.writerow([section_name, key, value, index])
    return buffer.getvalue()


def write_quality_report_file(
    path: str | Path,
    *,
    title: str,
    summary: dict[str, Any],
    sections: list[dict[str, Any]],
    format: str | None = None,
) -> Path:
    """Write a quality report in html, markdown, or csv format."""
    output = Path(path)
    resolved_format = format or output.suffix.lower().lstrip(".")
    if resolved_format in {"html", "htm"}:
        content = generate_quality_report_html(title=title, summary=summary, sections=sections)
    elif resolved_format in {"md", "markdown"}:
        content = generate_quality_report_markdown(title=title, summary=summary, sections=sections)
    elif resolved_format == "csv":
        content = generate_quality_report_csv(sections=sections)
    else:
        raise ValueError("Unsupported report format. Use html, md, or csv")
    output.write_text(content, encoding="utf-8")
    return output


__all__ = [
    "generate_quality_report_csv",
    "generate_quality_report_html",
    "generate_quality_report_markdown",
    "write_quality_report",
    "write_quality_report_file",
]
