"""Excel export for admin danh sách sáng kiến (TT / MSSK: «YYYY-n» theo năm hồ sơ)."""

from __future__ import annotations

from collections import defaultdict
from datetime import datetime, timezone
from io import BytesIO
from typing import Any, Dict, List, Tuple

import pandas as pd


def _calendar_year(row: Dict[str, Any]) -> int:
    cy = row.get("calendarYear")
    if isinstance(cy, int) and cy > 1900:
        return cy
    sd = str(row.get("submittedDate") or "")
    if len(sd) >= 4 and sd[:4].isdigit():
        return int(sd[:4])
    return datetime.now(timezone.utc).year


def _merit_xep_loai(row: Dict[str, Any]) -> str:
    """Aligned with fe0 «Đã duyệt»: 2.1.1 / 2.1.2 và Xuất sắc — Sách giáo trình → Xuất sắc; otherwise approved → Khá."""
    if str(row.get("status") or "") != "approved":
        return ""
    ic = row.get("initiativeClassification")
    rek = str(row.get("researchEvidenceKind") or row.get("research_evidence_kind") or "")
    tek = str(row.get("textbookEvidenceKind") or row.get("textbook_evidence_kind") or "")
    if ic == "research" and rek in ("international", "domestic"):
        return "Xuất sắc"
    if ic == "textbook" and tek == "book":
        return "Xuất sắc"
    if ic in ("research", "textbook", "technical"):
        return "Khá"
    return "Khá"


def _authors_cell(row: Dict[str, Any], payload: Dict[str, Any]) -> str:
    tabs = payload.get("tabs") if isinstance(payload.get("tabs"), dict) else {}
    app_tab = tabs.get("application") if isinstance(tabs.get("application"), dict) else {}
    authors = app_tab.get("authors")
    if isinstance(authors, list) and authors:
        names: List[str] = []
        for a in authors:
            if isinstance(a, dict):
                n = str(a.get("name") or "").strip()
                if n:
                    names.append(n)
        if names:
            return ", ".join(names)
    author = row.get("author") or {}
    single = str((author.get("name") if isinstance(author, dict) else "") or "").strip()
    return single or "—"


def _year_stt_codes(pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]]) -> List[str]:
    """Per calendar year, running index 1..n → «2026-1», «2026-2», …"""
    by_year: Dict[int, int] = defaultdict(int)
    out: List[str] = []
    for row, _ in pairs:
        y = _calendar_year(row)
        by_year[y] += 1
        out.append(f"{y}-{by_year[y]}")
    return out


def build_applications_list_xlsx(pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]]) -> bytes:
    """
    One sheet, headers: TT, MSSK, Tên sáng kiến, Tác giả, Xếp loại.
    TT and MSSK both use «YYYY-n» (n resets each calendar year, export order).
    """
    codes = _year_stt_codes(pairs)
    rows_out: List[Dict[str, Any]] = []
    for i, (row, payload) in enumerate(pairs):
        code = codes[i]
        rows_out.append(
            {
                "TT": code,
                "MSSK": code,
                "Tên sáng kiến": str(row.get("name") or ""),
                "Tác giả": _authors_cell(row, payload),
                "Xếp loại": _merit_xep_loai(row),
            }
        )
    df = pd.DataFrame(rows_out)
    buf = BytesIO()
    with pd.ExcelWriter(buf, engine="openpyxl") as writer:
        df.to_excel(writer, index=False, sheet_name="Danh sách")
    return buf.getvalue()
