#!/usr/bin/env perl
use strict;
use warnings;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";

# Invoked by cron every 5 minutes (recommended: */5 * * * *).
# Checks whether it's time to send the morning digest; exits silently otherwise.
# Guards against duplicate sends with last_digest_sent in the config table.
#
# Usage:
#   mnemosyne-digest [--config /path/to/mnemosyne.conf]

use Mnemosyne::Config;
use Mnemosyne::DB;
use Mnemosyne::Telegram;
use Mnemosyne::Digest;
use DateTime;
use DateTime::TimeZone;

use constant WINDOW_MINUTES => 5;   # half-window each side of digest_time

my $config_path = "$RealBin/../config/mnemosyne.conf";
while (@ARGV) {
    my $arg = shift @ARGV;
    if ($arg eq '--config' && @ARGV) { $config_path = shift @ARGV }
    else { die "Unknown argument: $arg\n" }
}

die "Config file not found: $config_path\n" unless -f $config_path;
my $config = Mnemosyne::Config->new($config_path);
my $db     = Mnemosyne::DB->new($config->get('db', 'path'));

# ---- current local time -----------------------------------------------
my $tz_name = $db->config_get('timezone') // 'UTC';
my $now     = eval { DateTime->now(time_zone => $tz_name) }
           // do { warn "Unknown timezone '$tz_name', falling back to UTC\n";
                   DateTime->now(time_zone => 'UTC') };

# ---- configured digest time -------------------------------------------
my $digest_time = $db->config_get('digest_time') // '06:30';
my ($dh, $dm)   = split /:/, $digest_time;
$dh //= 6; $dm //= 30;

# ---- check window: |now - digest_time| ≤ WINDOW_MINUTES ---------------
my $target = $now->clone->truncate(to => 'day')
                 ->add(hours => $dh + 0, minutes => $dm + 0);
my $diff   = abs(($now->epoch - $target->epoch) / 60);   # minutes

unless ($diff <= WINDOW_MINUTES) {
    exit 0;   # not time yet (or already past the window)
}

# ---- guard: already sent today? ---------------------------------------
my $today_str = $now->strftime('%Y-%m-%d');
my $last_sent = $db->config_get('last_digest_sent') // '';
if ($last_sent eq $today_str) {
    exit 0;   # already sent
}

# ---- send! ------------------------------------------------------------
my $token    = $config->get('bot', 'token')    or die "bot.token missing\n";
my $chat_id  = ($config->allowed_chat_ids)[0]  or die "No allowed_chat_ids in config\n";
my $telegram = Mnemosyne::Telegram->new($token);
my $today_dt = $now->clone->truncate(to => 'day');

eval {
    Mnemosyne::Digest->send($db, $telegram, $chat_id, $today_dt);
};
if ($@) {
    warn "Digest send failed: $@\n";
    exit 1;
}

exit 0;
