#!/usr/bin/env perl
use v5.36;
use strict;
use warnings;
use experimental 'try';
use lib 'lib','local/lib/perl5';
use Path::Tiny;
use JSON::MaybeXS;
use Dakkar::TweetArchive;
use Dakkar::NotesArchive;
use Dakkar::TweetArchive::Store;

my $json_parser = JSON::MaybeXS->new(
    utf8 => 1,
    relaxed => 1,
);

my $conf = $json_parser->decode(
    do {
        try {
            path(__FILE__)->sibling('tweet-archive.conf')->slurp_raw()
        }
        catch ($e) {
            '{}'
        }
    },
);

my $store = Dakkar::TweetArchive::Store->new($conf->{db});

if ($conf->{twitter} && $conf->{twitter}{enabled}) {
    my $client = Dakkar::TweetArchive->new($conf->{twitter});

    my @responses;
    $client->client->ua->add_handler( response_done => sub { push @responses, $_[0]; return } );

    try {
        my $latest_id = $store->latest_tweet_id;

        for my $tweet ($client->home_timeline($latest_id)->@*) {
            $store->store_tweet($tweet);
        }

        #$store->store_twitter_friends($client->friends);
        $store->store_twitter_followers($client->followers);
    }
    catch ($e) {
        print "Twitter Fail: $e\n";
        for my $res (@responses) {
            next if $res->is_success;
            print $res->request->as_string;
            print $res->as_string;
            print "\n",'-' x 50,"\n\n";
        }
    };
};

if ($conf->{misskey} && $conf->{misskey}{enabled}) {
    my $client = Dakkar::NotesArchive->new($conf->{misskey});

    my @responses;
    $client->client->ua->add_handler( response_done => sub { push @responses, $_[0]; return } );

    try {
        my $latest_id = $store->latest_note_id // '0';

        $client->timeline(
            $latest_id,
            sub($notes) {
                $store->store_note($_) for $notes->@*;
            },
        );

        $store->store_misskey_following($client->following);
        $store->store_misskey_followers($client->followers);
    }
    catch ($e) {
        print "Misskey Fail: $e\n";
        for my $res (@responses) {
            next if $res->is_success;
            print $res->request->as_string;
            print $res->as_string;
            print "\n",'-' x 50,"\n\n";
        }
    };
};

