% kpi-thesis-stats.sty — Totals for the annotation and project sheet.
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{kpi-thesis-stats}[2026/11/17 v2.0 Totals for the annotation and project sheet]

% Each document writes <jobname>.kpistats into its output folder; titles read them back.
\newcounter{kpi@figures}
\newcounter{kpi@tables}
\newcounter{kpi@sources}
\newcounter{kpi@appendices}
% Every numbered caption adds a line to the list of figures/tables (\caption* doesn't).
% Appendices count too, like their pages do.
\AddToHook{begindocument/end}{%
  \let\kpi@addcontentsline\addcontentsline
  \def\addcontentsline#1{%
    \kpi@countcaption{#1}%
    \kpi@addcontentsline{#1}}%
}

\ExplSyntaxOn
\cs_new_protected:Npn \kpi@countcaption #1
  {
    \str_if_eq:eeT {#1} {lof} { \stepcounter{kpi@figures} }
    \str_if_eq:eeT {#1} {lot} { \stepcounter{kpi@tables} }
  }
\ExplSyntaxOff

\newcount\kpi@shipped
\AddToHook{shipout/after}{\global\advance\kpi@shipped\@ne}
\newwrite\kpi@stats
\AtEndDocument{%
  \clearpage
  \immediate\openout\kpi@stats=\jobname.kpistats\relax
  \immediate\write\kpi@stats{\string\kpistat{pages}{\the\kpi@shipped}}%
  \immediate\write\kpi@stats{\string\kpistat{figures}{\the\value{kpi@figures}}}%
  \immediate\write\kpi@stats{\string\kpistat{tables}{\the\value{kpi@tables}}}%
  \immediate\write\kpi@stats{\string\kpistat{sources}{\the\value{kpi@sources}}}%
  \immediate\write\kpi@stats{\string\kpistat{appendices}{\the\value{kpi@appendices}}}%
  \immediate\closeout\kpi@stats
}

% \kpiloadstats{main}{../explanatory-note/build/explanatory-note.kpistats} then \kpistatof{main}{pages}; «??» until built.
\NewDocumentCommand\kpiloadstats{m m}{%
  \begingroup
  \def\kpistat##1##2{\global\@namedef{kpi@stat@#1@##1}{##2}}%
  \InputIfFileExists{#2}{}{}%
  \endgroup
}
\NewDocumentCommand\kpistatof{m m}{%
  \@ifundefined{kpi@stat@#1@#2}{\textbf{??}}{\@nameuse{kpi@stat@#1@#2}}%
}

\endinput
