#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use open qw(:utf8);
binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';
# Windows has no HOME; normalize once so every "$ENV{HOME}/..." below works
BEGIN { $ENV{HOME} //= $ENV{USERPROFILE} // '' }
use lib "$ENV{HOME}/.local/lib";
use lib 'lib';
use Module::Pluggable (
    search_path => 'App::Saisons::Adapter',
    require     => 1,
    inner       => 0,
);
use App::Saisons;
use App::Saisons::UI;
use App::Saisons::Launcher ();
use App::Saisons::Transfer ();
use Getopt::Long ();

my %opt;
Getopt::Long::GetOptions(\%opt, 'version', 'export:s', 'import=s', 'map=s@', 'clone!', 'dry-run')
    or die "Usage: saisons [--export [FILE]] [--import FILE [--map FROM=TO]... [--clone|--no-clone] [--dry-run]] [--version]\n";

if ($opt{version}) {
    print 'saisons ' . App::Saisons::version_string() . "\n";
    exit 0;
}

# ── load sessions from all adapters ──────────────────────────────────────────
# To add a new agent: see lib/App/Saisons/Adapter/HOWTO.md

my @adapters = map { $_->new }
               grep { $_->can('find_sessions') }
               plugins();

sub load_sessions {
    my (@sessions, %running);
    for my $adapter (@adapters) {
        push @sessions, $adapter->find_sessions;
        %running = (%running, $adapter->running);
    }
    @sessions = sort { $b->{date} cmp $a->{date} } @sessions;
    App::Saisons::UI::annotate_running(\@sessions, \%running);
    return (\@sessions, \%running);
}

# ── export / import ──────────────────────────────────────────────────────────

if (exists $opt{export}) {
    my ($sessions) = load_sessions();
    die "No sessions found.\n" unless @$sessions;
    my $file = length $opt{export} ? $opt{export} : App::Saisons::Transfer::default_file();
    my $r = App::Saisons::Transfer::export_sessions($sessions, $file);
    print map { "$_\n" } App::Saisons::Transfer::export_summary($r);
    exit 0;
}
if (defined $opt{import}) {
    my @results = App::Saisons::Transfer::import_bundle($opt{import}, \@adapters,
        clone => $opt{clone}, dry_run => $opt{'dry-run'},
        maps  => $opt{map} // []);
    exit((grep { $_->{status} eq 'error' } @results) ? 1 : 0);
}

# ── detect launcher ───────────────────────────────────────────────────────────

my $launcher = $ENV{SAISONS_LAUNCHER} // $ENV{CLAUDE_SESSIONS_LAUNCHER} // do {
    if    ($ENV{TMUX})                                          { 'tmux' }
    elsif ($ENV{STY})                                           { 'screen' }
    elsif ($ENV{EPITON_PANE_ID}
           && `which epiton 2>/dev/null` =~ /\S/)              { 'epiton' }
    elsif ($ENV{TILIX_ID}
           && `which tilix 2>/dev/null` =~ /\S/)               { 'tilix' }
    elsif ($ENV{PTYXIS_VERSION}
           && `which ptyxis 2>/dev/null` =~ /\S/)              { 'ptyxis' }
    elsif (($ENV{DISPLAY} || $ENV{WAYLAND_DISPLAY})
           && `which gnome-terminal 2>/dev/null` =~ /\S/)      { 'gnome-terminal' }
    elsif (($ENV{TERM_PROGRAM} // '') eq 'iTerm.app')          { 'iterm' }
    elsif ($^O eq 'darwin')                                     { 'terminal-app' }
    else                                                        { 'inline' }
};

# ── UI loop — keep running until user quits ───────────────────────────────────

my $ui = App::Saisons::UI->new;

while (1) {
    my ($sessions, $running) = load_sessions();
    die "No sessions found.\n" unless @$sessions;

    my @selected = $ui->interactive_select($sessions, $running, \&load_sessions);

    # Empty selection means the user pressed q/ESC — exit
    last unless @selected;

    # Launch selected sessions then loop back to the list
    my %by_adapter;
    for my $s (@selected) {
        push @{ $by_adapter{ ref $s->{_adapter} } }, $s;
    }
    App::Saisons::Launcher::batch($launcher, sub {
        for my $group (values %by_adapter) {
            $group->[0]{_adapter}->launch($group, $launcher);
        }
    });
}

__END__

=encoding utf8

=head1 NAME

saisons - browse and resume AI coding agent sessions from one list

=head1 SYNOPSIS

    saisons
    saisons --export [FILE]
    saisons --import FILE [--map FROM=TO]... [--clone | --no-clone] [--dry-run]
    saisons --version

=head1 DESCRIPTION

saisons lists the coding agent sessions it finds on the machine - Claude
Code, OpenAI Codex, Gemini CLI, Aider and opencode - in one terminal UI.
The list shows each session's agent, age, size, path and title, and can be
filtered, searched full-text, grouped and sorted.

Running sessions get a bullet: yellow while the agent is working (its
transcript was written in the last few seconds), green when it sits at the
prompt waiting for input.

Pressing ENTER resumes the selected sessions by running each agent's
resume command in the session's directory: in a new tmux or screen window,
a new terminal tab, or inline in the current terminal, depending on the
environment.

=head1 KEYS

    Up/Down, j/k     move            /        filter (title, path, date)
    PgUp/PgDn        page            ?        full-text search
    Home/End, g/G    top / bottom    Alt+C    toggle case sensitivity
    Space            toggle select   s        sort mode (arrows pick)
    a / A            select all/none S        flip sort direction
    ENTER            open selected   t        cycle grouping
    v                view history    r        refresh running markers
    d                delete          m        move to other directory
    f                fork and open the fork
    e                export to a file
    q / ESC          quit

With a filter or search active, ENTER, delete and move act only on the
selected sessions it shows. Export takes the marked sessions, or all shown
ones if none are marked.

=head1 MOVING SESSIONS TO ANOTHER MACHINE

C<--export> writes every session to one C<.tar.gz> file, named after the
host and date unless you give a name. Copy the file over and run
C<--import> there.

Import adds the sessions next to the ones already there and skips any
that are already there. Paths under the old home directory are changed to
the new one.

If other project folders live somewhere else on this machine, map them with
C<--map FROM=TO>, once per folder. A leading C<~> in TO is your home folder
here:

    saisons --import sessions.tar.gz --map '/projects=~/projects'

Before importing, it reports each project folder the sessions use: there,
missing with the C<git clone> command to get it back, missing and not in
git, or a repo that lacks the commit the source was on. It warns about
uncommitted and unpushed work on the source. It then offers to clone the
missing repos; C<--clone> and C<--no-clone> answer for you. C<--dry-run>
shows the report and imports nothing.

Aider sessions live in the project folder and are skipped until it
exists; import again once it does. Logins and API keys are not exported.

Sessions from opencode 1 can go into opencode 2, which converts them the
next time it starts; restart it after importing with
C<opencode service restart>.

=head1 FORKING

f copies the session under the cursor into a new session and opens it. It
asks for a folder, the session's own by default, and creates it when it is
missing; in a git repo it offers to make it a git worktree on a new branch.
If the folder already has sessions, their titles and checksums are shown
and you choose whether to add the fork anyway. The fork is listed under
the session it came from.

Claude Code, opencode 2 and Aider sessions can be forked. Aider keeps one
chat history per folder, so its fork needs a folder without one. An
opencode fork moves to its folder when it is opened.

=head1 SESSIONS THAT RAN OUT OF CONTEXT

When a Claude Code session runs out of context, it continues in a new
session. The list keeps them together: the old session on top, dimmed and
marked "ran out of context", and the one that took over under it (C<└>).
The cursor bar is a faded blue on the old session.
A session continued more than once shows each branch, the newest last.
Pressing ENTER on the old session offers to open the newest continuation
instead; n opens the old one anyway, ESC cancels.

=head1 ENVIRONMENT

=over 4

=item SAISONS_LAUNCHER

Where selected sessions open: C<tmux>, C<screen>, C<ptyxis>,
C<tilix>, C<epiton>, C<epiton-tile>, C<gnome-terminal>, C<iterm>,
C<terminal-app> or C<inline>. Without it, saisons picks one from the
environment; inside Epiton that is C<epiton>, which opens tabs, while
C<epiton-tile> lays the sessions out as tiles. The old name
C<CLAUDE_SESSIONS_LAUNCHER> still works.

=item SAISONS_SEARCH_DIRS

Directories to scan for Aider history files, separated like C<PATH>
(C<:>, or C<;> on Windows), instead of
the default project directories.

=back

=head1 AUTHOR

Nicolas Mendoza E<lt>mendoza@pvv.ntnu.noE<gt>

=head1 LICENSE

This software is licensed under the Artistic License 2.0.

=cut
