# pygacity latexmk configuration with pythontex support
#
# This profile is intended for use with:
#   build.pythontex-workflow: latexmkrc
#   build.latexmkrc-profile: pythontex
#
# Strategy: override $xelatex to run pythontex after each xelatex pass.
# pygacity sets PYGACITY_PYTHONTEX to the pythontex command it resolved
# (build.paths.pythontex); plain `pythontex` is the fallback.
#
# The standard add_cus_dep approach cannot work here.  latexmk requires the
# dep source and target to share the same stem, but the .pytxcode file lives
# in $out_dir/<job>.pytxcode while LaTeX needs
# pythontex-files-<job>/<job>.pytxmcr — different directory prefixes, so the
# stems never match and the dep never fires.

$xelatex = 'internal xelatex_pythontex %O %S';

sub xelatex_pythontex {
    # @_ is (%O expanded, %S expanded) — the full xelatex options string and
    # the source file.  Reconstruct and run the real xelatex command.
    my $ret = system("xelatex " . join(" ", @_));

    if ($ret == 0) {
        # Run pythontex if .pytxcode was generated into $out_dir.
        my $outdir = $out_dir || '.';
        $outdir =~ s{/+$}{};    # strip any trailing slashes
        if (-e "$outdir/$jobname.pytxcode") {
            my $pythontex = $ENV{'PYGACITY_PYTHONTEX'} || 'pythontex';
            my $pytx_ret = system("$pythontex \"$outdir/$jobname\"");
            if ($pytx_ret != 0) {
                # Fail the rule so the build stops instead of producing a
                # document with unresolved \py{} placeholders.
                warn "pygacity: pythontex failed on $outdir/$jobname (exit status $pytx_ret)\n";
                return $pytx_ret;
            }
        }
    }

    return $ret;
}

$clean_ext .= ' pytxcode pytxpyg pythontex_data.pkl';
