#!/usr/bin/perl

## make sure we can run this from the web interface
use lib qw(/home/ernad/ernad/perl /home/ernad/usr/share/perl /home/ernad/lib/perl);

use strict;
use warnings;

use Carp qw(cluck longmess shortmess croak confess);
#use File::Spec;
use Data::Dumper;
use Getopt::Std;
use List::Util qw(shuffle);

use Ernad::Args;
use Ernad::Common;
use Ernad::Constant;
use Ernad::Dates;
use Ernad::Editor;
use Ernad::Email;
use Ernad::Erimp;
use Ernad::Export;
use Ernad::Files;
use Ernad::Indat::Otria;
use Ernad::Indat::Report;
use Ernad::Pages;
use Krichel::File;

my %options;
&getopts('tmrnoh', \%options);
my $test_run=$options{'t'} // 0;
my $do_remail=$options{'m'} // 0;
my $do_reblatt=$options{'r'} // 0;
my $no_mail=$options{'n'} // 0;
## a new thing just for testing the rehopa faster
my $only_test_report_page=$options{'o'} // 0;
## change pages historically
my $historic=$options{'h'} // 0;

my $rif=$ARGV[0];
if(not $rif) {
  confess "I need a rif here.";
}
if(not -f $rif) {
  if(-f "$rif.gz") {
    $rif="$rif.gz";
  }
  else {
    confess "I can't open the rif $rif.";
  }
}

our ($impna, $e, $repcode, $in_file, $issuedate);
&Ernad::Args::parse();

$e=Ernad::Erimp->new({'impna'=> $impna, 'verbose'=>3});
my $rerc=$e->{'report'}->{$repcode};
if(not $rerc) {
  $e->{'r'}->load($repcode, {'enabled'=>0});
  $rerc=$e->{'report'}->{$repcode};
}
if(not $rerc) {
  confess "I don't know about your report '$repcode'.";
}

## no publishing at all
my $no_publish=$e->{'report'}->{$repcode}->{'no_publish'};
if(defined($no_publish) and $no_publish) {
  $e->echo(__LINE__,"Report $repcode is configured not to be published.");
  exit;
}

my $rix = &Krichel::File::load($rif);
# # update in doc require rs
my $rs={};
$rs->{'e'}=$e;
$rs->{'repcode'}=$repcode;
$rix=&Ernad::Editor::update_in_doc($rix,$rs,'do_add');
&Ernad::Files::save_if_diff($rif,$rix);
## costomize rif, usually for delivery URL acounting
my $custom_sheet_name='customize_rif';
my $custom_sheet_fufi=$e->{'dir'}->{'style'}.'/'.$custom_sheet_name.'.xslt.xml';
if(-f $custom_sheet_fufi) {
  $rix=$e->{'t'}->transform($rix,$custom_sheet_name,{'repcode'=>"'$repcode'"});
}

my $xp=$e->{'xpc'};
## check that there are papers in the issue
my $count_papers=$xp->findvalue('count(//amf:text)',$rix);
# unconditonal publish NOT replaced by rehopa
if($count_papers==0) {
  ## no papers, no sending
  $e->echo(__LINE__,"I see no papers in the rif $rif.");
  if(not $e->{'conf'}->{'no_blatt'}) {
    &unconditional_publish();
  }
  exit;
}

## uses $rix
if(not $no_mail) {
  &make_mail_from_rix($rix);
}
if(not $e->{'conf'}->{'no_rss'}) {
  ## uses $rix
  &make_rss_from_rix($rix);
}
if(not $e->{'conf'}->{'no_blatt'}) {
  # # this should work
  &make_blatt($repcode);
  # # this limit makes sense
  #print("start unconditioanl publish\n");
  #if($historic or $e->{'r'}->is_it_enabled($repcode)) {
  #  &unconditional_publish();
  #}
  #print("end unconditioanl publish\n");
}

## make exports
if(not $e->{'conf'}->{'no_export'}) {
  &Ernad::Export::public_amf_from_rix($rif,$rix,$repcode,$issuedate,$e);
  $e->echo(__LINE__,"I finished the exports.");
}

if($no_mail) {
  exit;
}

## nitpo comes last
my $bin_dir=$e->{'dir'}->{'bin'};
my $nitpo_script="$bin_dir/nitpo";
if(not -f $nitpo_script) {
  exit;
}
# # the following is done by Ernad::System
#my $pp=$e->{'dir'}->{'home'} . '/ernad/python';
#my $npp=$e->{'conf'}->{'nitpo_pythonpath'} // '';
#if($npp) {
#  $pp.=":$npp";
#}
#my $s="export HOME=" . $e->{'dir'}->{'home'} . "; ";
#if($pp) {
#  $s="export PYTHONPATH=$pp ; "
#}
my $s="$nitpo_script $rif";
if($do_remail) {
  $s="$nitpo_script -p  $rif";
}
# # hopefully into the log
print("$s\n");
system($s);

## run report_sborn here, otherwise the information is outdated.
## FixMe

if(not $e->{'conf'}->{'no_blatt'}) {
  # # this should work
  if($historic or $e->{'r'}->is_it_enabled($repcode)) {
    &unconditional_publish();
  }
  else {
    warn("I don't run report_sborn for $repcode");
  }
}

# warn("I should be done");
$e->{'y'}->run('report_sborn',{'arg'=>$rif, 'do_wait'=>1, 'add_log'=>$repcode});

## publication routines that hold for empty and full issues
sub unconditional_publish {
  ##
  ## 2025-08-23 only run sborn
  if($impna ne 'nep') {
    $e->{'y'}->run('report_sborn',{'arg'=>$rif, 'do_wait'=>1, 'add_log'=>$repcode});
  }
  return;
#  ## still have to run the indat, same code as below
#  ## FixMe: This should be replaced a library call once
#  ## vypot_indat is stable, and run_system() deleted from Ernad::Erimp
#  if(not $only_test_report_page) {
#    $e->{'y'}->run('vypot_indat',{'arg'=>$rif, 'do_wait'=>1, 'add_log'=>$repcode});
#  }
#  ## FixMe: This code is copied in perl/report_blatt
#  my $r=Ernad::Indat::Report->new();
#  ## so we don't have to run the otria twice
#  my $report_list=$r->gather_active_reports();
#  my $is_it_active=0;
#  ## add repcode, for Sebastian Hofer
#  #if ( ! grep(/^$repcode$/, @{$report_list})) {
#  #  push(@$report_list, $repcode);
#  #}
#  # my $report_list_lafise=$r->gather_all_reports('by_lafise');
#  my $s=Ernad::Indat::Sborn->new();
#  #my $s_lafise=Ernad::Indat::Sborn->new();
#  my $doc;
#  ## double-try with .gz
#  if(not -f $rif) {
#    if(-f "$rif.gz") {
#      $rif="$rif.gz";
#    }
#  }
#  my $time=&Ernad::Dates::mtime_string($rif);
#  if(not $only_test_report_page and $impna ne 'nep') {
#    $doc=$s->report_xml($report_list);
#    $doc->toFile('/tmp/sborn.xml');
#    $s->show('reports',$doc);
#  }
}

sub make_mail_from_rix {
  my $rix=shift;
  my $issuedate=$e->{'f'}->issuedate($rif);
  # # at 2022-04-04
  if (! $e->{'conf'}->{'email_repis_to_list'} and
      ! $e->{'conf'}->{'email_repis_to_editors'}) {
    return;
  }
  my $webvault_dir=$e->{'conf'}->{'mailvault_dir'} or die;
  my $save_email=$e->{'dir'}->{'web'}.'/'.$webvault_dir.'/'.$repcode.'/'.$issuedate;
  my $mail_file="$save_email.mail";
  my $no_remail=0;
  if (-f $mail_file and not $do_remail and not $test_run) {
    $e->echo(__LINE__,"I see $mail_file, but no -m option. I prepare but not remail.");
    $no_remail=1;
  }
  ## let's check if we have a from address
  my $editor_email=$rerc->{'editor_email'} or
    confess "I don't see an editor email.";
  my $email_file=Ernad::Email::prepare_email($rix,'issue',$save_email);
  my $no_mail=$e->{'report'}->{$repcode}->{'no_mail'};
  if(defined($no_publish) and $no_publish) {
    $e->{'report'}->{$repcode}->{'no_mail'}=1;
  }
  if(not (defined($no_mail) and $no_mail)
     and not $test_run
     and not $no_remail) {
    $e->echo(__LINE__,"I am sending $email_file.");
    &Ernad::Email::send_email($email_file);
  }
  else {
    $e->echo(__LINE__,"I did not send email.");
  }
}

sub make_rss_from_rix {
  my $rix=shift;
  my $rss_style_file=$e->{'dir'}->{'style'}.'/rss.xslt.xml';
  if(not -f $rss_style_file) {
    $e->echo(__LINE__,"I don't see $rss_style_file. I won't make rss feeds.");
    return 0;
  }
  my $rss_doc=$e->{'t'}->transform($rix,'rss');
  my $rss_dir=$e->{'conf'}->{'rss_dir'} or die;
  my $rss_file="$rss_dir/$repcode.rss.xml";
  &Krichel::File::prepare($rss_file);
  &Ernad::Files::save_xml_with_temp($rss_file,$rss_doc);
  return 1;
}

sub make_blatt {
  if($e->{'conf'}->{'no_blatt'}) {
    return;
  }
  my $papers=&issue_blatt($repcode,$do_reblatt);
  # # here we have to stop for disabled
  if(not $e->{'r'}->is_it_enabled($repcode)) {
    $e->echo(__LINE__,"I only did the issue blatt because $repcode is disabled.",1);
    return;
  }
  my $doc=$e->{'r'}->doc($repcode);
  my $amf_ns=$Ernad::Constant::c->{'amf_ns'} // confess "I don't see the amf_ns";
  my $report_ele=$doc->getElementsByTagNameNS($amf_ns,'collection')->[0];
  if(not $report_ele) {
    confess "I don't see a main collection in $doc.";
  }
  foreach my $date (reverse sort keys %$papers) {
    my $colpart_ele=$doc->createElementNS($amf_ns,'haspart');
    $colpart_ele->setAttribute('from',$date);
    $colpart_ele->setAttribute('until',$date);
    my $issue_ele=$doc->createElementNS($amf_ns,'collection');
    my $count_texts=0;
    foreach my $pid (@{$papers->{$date}}) {
      my $haspart_ele=$doc->createElementNS($amf_ns,'haspart');
      my $paper_ele=$doc->createElementNS($amf_ns,'text');
      $count_texts++;
      $paper_ele->setAttribute('ref',$pid);
      $haspart_ele->appendTextNode("\n");
      $haspart_ele->addChild($paper_ele);
      $haspart_ele->appendTextNode("\n");
      $issue_ele->addChild($haspart_ele);
      $issue_ele->appendTextNode("\n");
      $colpart_ele->addChild($issue_ele);
      $colpart_ele->appendTextNode("\n");
    }
    if(not $count_texts) {
      next;
    }
    $report_ele->addChild($colpart_ele);
    $report_ele->appendTextNode("\n");
  }
  my $rss_doc=$e->{'t'}->transform($doc,'rss');
  my $out_file=$e->{'report'}->{$repcode}->{'dir'}->{'blatt'}.'/rss.xml';
  &Krichel::File::prepare($out_file);
  $rss_doc->toFile($out_file);
  $e->echo(__LINE__,"I wrote $out_file.");
}

### the invidual web page of an issue, replaced by rehopa
sub issue_blatt {
  my $repcode=shift // $e->{'repcode'} // confess "I need a repcode.";
  my $do_redo=shift // '';
  my $rerc=$e->{'report'}->{$repcode}  // confess "I don't know about your repcode '$repcode'.";
  my $sent_dir=$rerc->{'dir'}->{'sent'};
  my $rifs=$e->{'d'}->get_latest_rif_from_each_issue_in_subdir($sent_dir);
  my $p;
  my $blatt_dir=$rerc->{'dir'}->{'blatt'};
  foreach my $rif (shuffle @$rifs) {
    ## if the rif has been compress, rerif
    if(not -f $rif) {
      if(-f "$rif.gz") {
        $rif="$rif.gz";
      }
      else {
        confess "I don't see your rif $rif";
      }
    }
    my $issuedate=$e->{'f'}->issuedate($rif);
    my $out_file="$blatt_dir/$issuedate.html";
    my $papers=$e->{'x'}->papids($rif,'array');
    $p->{$issuedate}=$papers;
    if(not $papers) {
      $e->echo(__LINE__,"The rif $rif is empty.");
      if(-f $out_file) {
        $e->echo(__LINE__,"I remove the file $out_file.");
        unlink $out_file;
      }
      next;
    }
    if(not $do_redo and not &Ernad::Common::does_file_need_renewal($out_file,$rif)) {
      next;
    }
  }
  return $p;
}
