from __future__ import annotations

import json
from html import escape
from pathlib import Path

import pandas as pd

BACKEND_DIR = Path(__file__).resolve().parents[1]
ROOT_DIR = BACKEND_DIR.parent
GOLD_DIR = ROOT_DIR / "data" / "gold"
DASHBOARD_DIR = ROOT_DIR / "frontend"
OUTPUT_PATH = DASHBOARD_DIR / "index.html"
YEAR = 2026
MISSING_LABEL = "S/ Nota"
FILLED_LABEL = "C/ Nota"
ALL_VALUE = "__all__"


def read_gold(name: str) -> pd.DataFrame:
    return pd.read_parquet(GOLD_DIR / f"{name}_{YEAR}.parquet")


def format_pt(value: int | float) -> str:
    return f"{value:,}".replace(",", ".")


def records_from_series(series: pd.Series) -> list[dict]:
    return [{"label": str(index), "value": int(value)} for index, value in series.items()]


def status_breakdown(df: pd.DataFrame, group_col: str, top_n: int | None = None) -> list[dict]:
    grouped = (
        df.pivot_table(
            index=group_col,
            columns="CONTAGEM_NOTAS",
            values="RA",
            aggfunc="size",
            fill_value=0,
        )
        .reset_index()
        .rename_axis(None, axis=1)
    )

    for col in [MISSING_LABEL, FILLED_LABEL]:
        if col not in grouped.columns:
            grouped[col] = 0

    grouped["TOTAL"] = grouped[MISSING_LABEL] + grouped[FILLED_LABEL]
    grouped["PCT_SEM_NOTA"] = grouped[MISSING_LABEL] / grouped["TOTAL"]
    grouped = grouped.sort_values([MISSING_LABEL, "PCT_SEM_NOTA"], ascending=False)

    if top_n:
        grouped = grouped.head(top_n)

    return [
        {
            "label": str(row[group_col]),
            "missing": int(row[MISSING_LABEL]),
            "filled": int(row[FILLED_LABEL]),
            "total": int(row["TOTAL"]),
            "missingPct": round(float(row["PCT_SEM_NOTA"]) * 100, 1),
        }
        for _, row in grouped.iterrows()
    ]


def build_view(lancamento: pd.DataFrame) -> dict:
    contagem = lancamento["CONTAGEM_NOTAS"].fillna("Sem valor").value_counts()
    total = int(len(lancamento))
    missing = int(contagem.get(MISSING_LABEL, 0))
    filled = int(contagem.get(FILLED_LABEL, 0))
    missing_pct = round((missing / total) * 100, 1) if total else 0
    filled_pct = round((filled / total) * 100, 1) if total else 0
    affected_students = int(
        lancamento.loc[lancamento["CONTAGEM_NOTAS"] == MISSING_LABEL, "RA"].nunique()
    )

    missing_df = lancamento[lancamento["CONTAGEM_NOTAS"] == MISSING_LABEL].copy()

    return {
        "kpis": [
            {
                "label": "Lancamentos esperados",
                "value": format_pt(total),
                "detail": "Total depois da regra DEVE_SER_MEDIDO = S",
            },
            {
                "label": "Sem nota",
                "value": format_pt(missing),
                "detail": f"{missing_pct}% dos lancamentos esperados",
            },
            {
                "label": "Com nota",
                "value": format_pt(filled),
                "detail": f"{filled_pct}% preenchidos",
            },
            {
                "label": "Alunos afetados",
                "value": format_pt(affected_students),
                "detail": "RAs com ao menos uma nota faltando",
            },
        ],
        "charts": {
            "contagemNotas": records_from_series(
                contagem.reindex([MISSING_LABEL, FILLED_LABEL]).fillna(0)
            ),
            "series": status_breakdown(lancamento, "SERIE"),
            "etapas": status_breakdown(lancamento, "ETAPA_LABEL"),
            "digitacao": status_breakdown(lancamento, "DIGITACAO_LABEL"),
            "disciplinas": records_from_series(
                missing_df["DISCIPLINA_LABEL"].value_counts().head(12)
            ),
            "turmas": records_from_series(missing_df["CODTURMA"].value_counts().head(12)),
        },
    }


def view_key(unidade_value: str, etapa_value: str) -> str:
    return f"{unidade_value}|{etapa_value}"


def build_payload() -> dict:
    lancamento = read_gold("lancamento_notas")
    dim_disciplinas = read_gold("dim_disciplinas")
    dim_etapas = read_gold("dim_etapas")
    dim_unidades = read_gold("dim_unidades")

    required_cols = [
        "CONTAGEM_NOTAS",
        "RA",
        "SERIE",
        "CODTURMA",
        "CODCOLIGADA",
        "CODDISC",
        "CODETAPA",
    ]
    missing_cols = [col for col in required_cols if col not in lancamento.columns]
    if missing_cols:
        raise ValueError(f"Colunas ausentes em lancamento_notas gold: {missing_cols}")

    lancamento = lancamento.merge(dim_etapas, on="CODETAPA", how="left")
    lancamento = lancamento.merge(dim_disciplinas, on="CODDISC", how="left")

    lancamento["ETAPA_LABEL"] = (
        lancamento["ETAPA"].fillna(lancamento["CODETAPA"]).fillna("Sem etapa")
    )
    lancamento["DISCIPLINA_LABEL"] = (
        lancamento["DISCIPLINA"].fillna(lancamento["CODDISC"]).fillna("Sem disciplina")
    )
    lancamento["DIGITACAO_LABEL"] = (
        lancamento["DIGITACAO_PELO_PROFESSOR"].fillna("Sem valor")
    )

    dim_etapas_sorted = dim_etapas.assign(
        CODETAPA_SORT=pd.to_numeric(dim_etapas["CODETAPA"], errors="coerce")
    ).sort_values(["CODETAPA_SORT", "CODETAPA"])

    etapa_options = [
        {"value": str(row["CODETAPA"]), "label": str(row["ETAPA"])}
        for _, row in dim_etapas_sorted.iterrows()
    ]

    unidade_options = [
        {"value": str(row["CODCOLIGADA"]), "label": str(row["FILIAL"])}
        for _, row in dim_unidades.sort_values("FILIAL").iterrows()
    ]

    views = {}
    unidade_values = [ALL_VALUE] + [option["value"] for option in unidade_options]
    etapa_values = [ALL_VALUE] + [option["value"] for option in etapa_options]

    lancamento["CODCOLIGADA_FILTER"] = lancamento["CODCOLIGADA"].astype(str)
    lancamento["CODETAPA_FILTER"] = lancamento["CODETAPA"].astype(str)

    for unidade_value in unidade_values:
        for etapa_value in etapa_values:
            filtered = lancamento
            if unidade_value != ALL_VALUE:
                filtered = filtered[filtered["CODCOLIGADA_FILTER"] == unidade_value]
            if etapa_value != ALL_VALUE:
                filtered = filtered[filtered["CODETAPA_FILTER"] == etapa_value]

            views[view_key(unidade_value, etapa_value)] = build_view(filtered)

    return {
        "year": YEAR,
        "allValue": ALL_VALUE,
        "unidadeOptions": unidade_options,
        "etapaOptions": etapa_options,
        "views": views,
    }


def render_html(payload: dict) -> str:
    payload_json = json.dumps(payload, ensure_ascii=False)

    return f"""<!doctype html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Painel de Lancamento de Notas</title>
  <style>
    :root {{
      color-scheme: light;
      --bg: #f4f6f8;
      --panel: #ffffff;
      --text: #1f2933;
      --muted: #667085;
      --line: #d9e2ec;
      --missing: #c05621;
      --filled: #2f855a;
      --blue: #1d6fb8;
      --gold: #b7791f;
    }}

    * {{ box-sizing: border-box; }}

    body {{
      margin: 0;
      font-family: Arial, Helvetica, sans-serif;
      background: var(--bg);
      color: var(--text);
    }}

    header {{
      padding: 24px 32px 16px;
      border-bottom: 1px solid var(--line);
      background: var(--panel);
    }}

    h1 {{
      margin: 0;
      font-size: 26px;
      font-weight: 700;
      letter-spacing: 0;
    }}

    header p, .panel p {{
      margin: 6px 0 0;
      color: var(--muted);
      font-size: 14px;
    }}

    main {{
      padding: 24px 32px 40px;
      max-width: 1440px;
      margin: 0 auto;
    }}

    .kpis {{
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 16px;
      margin-bottom: 22px;
    }}

    .filters {{
      display: flex;
      flex-wrap: wrap;
      align-items: end;
      gap: 14px;
      margin-bottom: 18px;
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: 8px;
      padding: 14px 16px;
    }}

    .field {{
      display: grid;
      gap: 6px;
    }}

    .field label {{
      color: var(--muted);
      font-size: 13px;
    }}

    select {{
      min-width: 220px;
      height: 36px;
      border: 1px solid var(--line);
      border-radius: 6px;
      background: #ffffff;
      color: var(--text);
      padding: 0 10px;
      font-size: 14px;
    }}

    .kpi, .panel {{
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: 8px;
    }}

    .kpi {{
      padding: 16px;
      min-height: 112px;
    }}

    .kpi span {{
      display: block;
      color: var(--muted);
      font-size: 13px;
    }}

    .kpi strong {{
      display: block;
      margin-top: 12px;
      font-size: 30px;
      line-height: 1;
    }}

    .kpi small {{
      display: block;
      margin-top: 10px;
      color: var(--muted);
      font-size: 12px;
    }}

    .grid {{
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 16px;
    }}

    .panel {{
      padding: 16px;
      min-height: 350px;
    }}

    .wide {{
      grid-column: 1 / -1;
    }}

    .panel h2 {{
      margin: 0;
      font-size: 17px;
      letter-spacing: 0;
    }}

    .chart, .bars, .stacked {{
      margin-top: 16px;
    }}

    .bar-row, .stack-row {{
      display: grid;
      grid-template-columns: minmax(120px, 210px) 1fr 92px;
      align-items: center;
      gap: 12px;
      min-height: 25px;
      font-size: 13px;
    }}

    .bar-label {{
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }}

    .bar-track, .stack-track {{
      height: 13px;
      background: #eef2f6;
      border-radius: 999px;
      overflow: hidden;
      display: flex;
    }}

    .bar-fill {{
      height: 100%;
      width: var(--width);
      background: var(--color);
    }}

    .stack-missing {{
      height: 100%;
      width: var(--missing-width);
      background: var(--missing);
    }}

    .stack-filled {{
      height: 100%;
      width: var(--filled-width);
      background: var(--filled);
    }}

    .bar-value {{
      text-align: right;
      color: var(--muted);
      font-variant-numeric: tabular-nums;
    }}

    .legend {{
      display: flex;
      gap: 16px;
      margin-top: 12px;
      color: var(--muted);
      font-size: 13px;
    }}

    .legend span::before {{
      content: "";
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 2px;
      margin-right: 6px;
      background: var(--legend-color);
    }}

    svg text {{
      fill: var(--muted);
      font-size: 12px;
    }}

    @media (max-width: 980px) {{
      header, main {{ padding-left: 18px; padding-right: 18px; }}
      .kpis, .grid {{ grid-template-columns: 1fr; }}
      .wide {{ grid-column: auto; }}
      .bar-row, .stack-row {{ grid-template-columns: minmax(88px, 132px) 1fr 78px; }}
    }}
  </style>
</head>
<body>
  <header>
    <h1>Painel de Lancamento de Notas</h1>
    <p>Diagnostico principal por CONTAGEM_NOTAS para {escape(str(payload["year"]))}</p>
  </header>

  <main>
    <section class="filters">
      <div class="field">
        <label for="unidadeSelect">Unidade</label>
        <select id="unidadeSelect"></select>
      </div>

      <div class="field">
        <label for="etapaSelect">Etapa</label>
        <select id="etapaSelect"></select>
      </div>
    </section>

    <section id="kpis" class="kpis">
    </section>

    <section class="grid">
      <article class="panel">
        <h2>Situacao geral</h2>
        <p>Com nota versus sem nota em lancamento_notas</p>
        <div id="contagemNotas" class="chart"></div>
      </article>

      <article class="panel">
        <h2>Digitacao pelo professor</h2>
        <p>Situacao das notas por regra de digitacao</p>
        <div id="digitacao" class="stacked"></div>
      </article>

      <article class="panel wide">
        <h2>Situacao por serie</h2>
        <p>Volume e percentual sem nota por serie</p>
        <div class="legend">
          <span style="--legend-color: var(--filled)">Com nota</span>
          <span style="--legend-color: var(--missing)">Sem nota</span>
        </div>
        <div id="series" class="stacked"></div>
      </article>

      <article class="panel">
        <h2>Situacao por etapa</h2>
        <p>Volume de notas faltantes em cada etapa</p>
        <div id="etapas" class="stacked"></div>
      </article>

      <article class="panel">
        <h2>Disciplinas com mais notas faltando</h2>
        <p>Top 12 disciplinas por S/ Nota</p>
        <div id="disciplinas" class="bars"></div>
      </article>

      <article class="panel">
        <h2>Turmas com mais notas faltando</h2>
        <p>Top 12 turmas por S/ Nota</p>
        <div id="turmas" class="bars"></div>
      </article>
    </section>
  </main>

  <script>
    const payload = {payload_json};
    const colors = ["#c05621", "#2f855a", "#1d6fb8", "#b7791f"];

    function formatNumber(value) {{
      return new Intl.NumberFormat("pt-BR").format(value);
    }}

    function drawDonut(id, data) {{
      const container = document.getElementById(id);
      const total = data.reduce((sum, item) => sum + item.value, 0);
      if (!data.length || total === 0) {{
        container.innerHTML = `<p>Nenhum dado para a etapa selecionada.</p>`;
        return;
      }}
      const size = 260;
      const radius = 88;
      const center = size / 2;
      const stroke = 34;
      const circumference = 2 * Math.PI * radius;
      let offset = 0;

      const segments = data.map((item, index) => {{
        const fraction = total ? item.value / total : 0;
        const dash = fraction * circumference;
        const segment = `<circle cx="${{center}}" cy="${{center}}" r="${{radius}}" fill="none"
          stroke="${{colors[index % colors.length]}}" stroke-width="${{stroke}}"
          stroke-dasharray="${{dash}} ${{circumference - dash}}"
          stroke-dashoffset="${{-offset}}" transform="rotate(-90 ${{center}} ${{center}})" />`;
        offset += dash;
        return segment;
      }}).join("");

      const legend = data.map((item, index) => `
        <div class="bar-row">
          <span class="bar-label">${{item.label}}</span>
          <span class="bar-track"><span class="bar-fill" style="--width: 100%; --color: ${{colors[index % colors.length]}}"></span></span>
          <span class="bar-value">${{formatNumber(item.value)}}</span>
        </div>
      `).join("");

      container.innerHTML = `
        <div style="display:grid;grid-template-columns:260px 1fr;gap:14px;align-items:center;">
          <svg width="${{size}}" height="${{size}}" viewBox="0 0 ${{size}} ${{size}}" role="img">
            <circle cx="${{center}}" cy="${{center}}" r="${{radius}}" fill="none" stroke="#eef2f6" stroke-width="${{stroke}}" />
            ${{segments}}
            <text x="${{center}}" y="${{center - 4}}" text-anchor="middle" style="font-size:24px;fill:#1f2933;font-weight:700">${{formatNumber(total)}}</text>
            <text x="${{center}}" y="${{center + 18}}" text-anchor="middle">total</text>
          </svg>
          <div class="bars">${{legend}}</div>
        </div>
      `;
    }}

    function drawBars(id, data, color = "#c05621") {{
      const container = document.getElementById(id);
      if (!data.length) {{
        container.innerHTML = `<p>Nenhum dado para a etapa selecionada.</p>`;
        return;
      }}
      const max = Math.max(...data.map((item) => item.value), 1);

      container.innerHTML = data.map((item) => {{
        const width = Math.max((item.value / max) * 100, 1);
        return `
          <div class="bar-row" title="${{item.label}}: ${{formatNumber(item.value)}}">
            <span class="bar-label">${{item.label}}</span>
            <span class="bar-track">
              <span class="bar-fill" style="--width: ${{width}}%; --color: ${{color}}"></span>
            </span>
            <span class="bar-value">${{formatNumber(item.value)}}</span>
          </div>
        `;
      }}).join("");
    }}

    function drawStacked(id, data) {{
      const container = document.getElementById(id);
      if (!data.length) {{
        container.innerHTML = `<p>Nenhum dado para a etapa selecionada.</p>`;
        return;
      }}

      container.innerHTML = data.map((item) => {{
        const missingWidth = item.total ? (item.missing / item.total) * 100 : 0;
        const filledWidth = item.total ? (item.filled / item.total) * 100 : 0;
        return `
          <div class="stack-row" title="${{item.label}}: ${{formatNumber(item.missing)}} sem nota de ${{formatNumber(item.total)}}">
            <span class="bar-label">${{item.label}}</span>
            <span class="stack-track">
              <span class="stack-filled" style="--filled-width: ${{filledWidth}}%"></span>
              <span class="stack-missing" style="--missing-width: ${{missingWidth}}%"></span>
            </span>
            <span class="bar-value">${{formatNumber(item.missing)}} · ${{item.missingPct}}%</span>
          </div>
        `;
      }}).join("");
    }}

    function renderKpis(kpis) {{
      const container = document.getElementById("kpis");
      container.innerHTML = kpis.map((kpi) => `
        <article class="kpi">
          <span>${{kpi.label}}</span>
          <strong>${{kpi.value}}</strong>
          <small>${{kpi.detail}}</small>
        </article>
      `).join("");
    }}

    function makeViewKey(unidadeValue, etapaValue) {{
      return `${{unidadeValue}}|${{etapaValue}}`;
    }}

    function renderDashboard() {{
      const unidadeValue = document.getElementById("unidadeSelect").value;
      const etapaValue = document.getElementById("etapaSelect").value;
      const view = payload.views[makeViewKey(unidadeValue, etapaValue)] || payload.views[makeViewKey(payload.allValue, payload.allValue)];
      renderKpis(view.kpis);
      drawDonut("contagemNotas", view.charts.contagemNotas);
      drawStacked("digitacao", view.charts.digitacao);
      drawStacked("series", view.charts.series);
      drawStacked("etapas", view.charts.etapas);
      drawBars("disciplinas", view.charts.disciplinas, "#c05621");
      drawBars("turmas", view.charts.turmas, "#b7791f");
    }}

    function populateSelect(selectId, allLabel, options) {{
      const select = document.getElementById(selectId);
      select.innerHTML = [
        `<option value="${{payload.allValue}}">${{allLabel}}</option>`,
        ...options.map((option) => (
          `<option value="${{option.value}}">${{option.label}}</option>`
        ))
      ].join("");

      select.addEventListener("change", renderDashboard);
    }}

    function populateFilters() {{
      populateSelect("unidadeSelect", "Todas as unidades", payload.unidadeOptions);
      populateSelect("etapaSelect", "Todas as etapas", payload.etapaOptions);
    }}

    populateFilters();
    renderDashboard();
  </script>
</body>
</html>
"""


def main() -> None:
    DASHBOARD_DIR.mkdir(parents=True, exist_ok=True)
    payload = build_payload()
    OUTPUT_PATH.write_text(render_html(payload), encoding="utf-8")
    print(f"Dashboard generated: {OUTPUT_PATH}")


if __name__ == "__main__":
    main()
