#!/usr/bin/env perl
use strict;
use warnings;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
use Getopt::Long qw(GetOptions);
use Bioconda::Packages;

=head1 NAME

bioconda-packages - Offline query tool for the bundled Bioconda package database

=head1 SYNOPSIS

    bioconda-packages <command> [args] [options]

    # Package information
    bioconda-packages info samtools
    bioconda-packages versions samtools

    # Dependencies
    bioconda-packages deps multiqc               # run-time deps (default)
    bioconda-packages deps multiqc --kind host   # host deps
    bioconda-packages deps multiqc --kind all    # all dep kinds

    # Reverse dependencies
    bioconda-packages rdeps zlib                 # who uses zlib at run time
    bioconda-packages rdeps zlib --kind build    # who uses it at build time
    bioconda-packages rdeps zlib --all           # include removed packages

    # Search & listing
    bioconda-packages search aligner
    bioconda-packages search aligner --all       # include removed packages
    bioconda-packages list
    bioconda-packages list --all

    # Database housekeeping
    bioconda-packages removed
    bioconda-packages stats
    bioconda-packages version

=head1 COMMANDS

=over 4

=item B<info> I<PACKAGE>

Print a summary for I<PACKAGE>: current version, one-line description, license,
homepage, documentation URL, noarch flag, download count, known identifiers, and
the number of run-time dependencies.

=item B<deps> I<PACKAGE>

List dependencies of I<PACKAGE>.  Defaults to run-time deps; use C<--kind> to
select C<run>, C<host>, C<build>, or C<all>.  Each line is C<name> or
C<name constraint>.

=item B<versions> I<PACKAGE>

List every version of I<PACKAGE> that is recorded in the database, one per line.

=item B<search> I<TERM>

Search package names and summaries for I<TERM> (case-insensitive substring
match) and print matching package names.  Pass C<--all> to include packages that
have been removed from the bioconda recipe tree.

=item B<rdeps> I<PACKAGE>

Print packages that depend on I<PACKAGE>.  Defaults to run-time reverse deps;
use C<--kind> (C<run>|C<host>|C<build>|C<all>).  Pass C<--all> to include
removed packages.

=item B<list>

Print the name of every package in the database, one per line.  Pass C<--all>
to include removed packages.

=item B<removed>

Print the names of all packages that have been removed from the bioconda recipe
tree but are still tracked in the database.

=item B<stats>

Print database statistics: version, total / current / removed package counts,
noarch count, build timestamp, and the upstream recipes commit.

=item B<version>

Print the tool version (C<Bioconda::Packages> module version) and, if the
database can be located, its version, file path, build timestamp, generator
identifier, package count, and the bioconda-recipes commit it was built from.

=back

=head1 OPTIONS

=over 4

=item B<--db> I<PATH>

Load the database from I<PATH> instead of the default location.  The default
search order is: (1) C<BIOCONDA_PACKAGES_DB> environment variable, (2)
C<File::ShareDir> installed location, (3) C<share/bioconda-packages.json.gz>
relative to the module file.

=item B<--kind> I<KIND>

Dependency kind for C<deps> and C<rdeps>.  One of C<run> (default), C<host>,
C<build>, or C<all>.

=item B<--all>

Include packages that have been removed from the bioconda recipe tree in
C<search>, C<list>, and C<rdeps> output.

=item B<--version>, B<-V>

Print the tool and database version, then exit.

=item B<--help>

Show this manual page and exit.

=back

=head1 ENVIRONMENT

=over 4

=item C<BIOCONDA_PACKAGES_DB>

Override the database path without using C<--db>.

=back

=head1 SEE ALSO

L<Bioconda::Packages>, L<Bioconda::Packages::Package>

=head1 AUTHOR

Andrea Telatin, Quadram Institute Bioscience (2026)

=cut

my %opt = (kind => undef, all => 0);
GetOptions(
    'db=s'       => \$opt{db},
    'kind=s'     => \$opt{kind},
    'all'        => \$opt{all},
    'version|V'  => \$opt{version},
    'help'       => \$opt{help},
) or die "Bad arguments. Try --help.\n";

exec('perldoc', $0) if $opt{help};

my $cmd = $opt{version} ? 'version' : (shift @ARGV or die usage());

# 'version' must work even if the database cannot be located.
if ($cmd eq 'version') { cmd_version(); exit 0 }

my $bp = Bioconda::Packages->new($opt{db} ? (db => $opt{db}) : ());

my %dispatch = (
    info     => \&cmd_info,
    deps     => \&cmd_deps,
    versions => \&cmd_versions,
    search   => \&cmd_search,
    rdeps    => \&cmd_rdeps,
    removed  => \&cmd_removed,
    stats    => \&cmd_stats,
    list     => \&cmd_list,
);

my $handler = $dispatch{$cmd} or die "Unknown command '$cmd'.\n", usage();
$handler->();

sub usage {
    return "Usage: bioconda-packages <info|deps|versions|search|rdeps|removed|list|stats|version> [args]\n";
}

sub cmd_version {
    printf "bioconda-packages (Bioconda::Packages) %s\n",
        Bioconda::Packages->VERSION // 'dev';
    my $bp = eval { Bioconda::Packages->new($opt{db} ? (db => $opt{db}) : ()) };
    if ($bp) {
        my $m = $bp->meta;
        printf "database version: %s\n", $m->{db_version} // '(unversioned)';
        printf "database:         %s\n", $bp->db_path;
        printf "  built from:     bioconda-recipes %s\n",
            $m->{recipes_commit} // 'unknown';
        printf "  generated at:   %s\n", $m->{generated_at}  // '-';
        printf "  packages:       %s\n", $m->{package_count} // '-';
        printf "  generator:      %s\n", $m->{generator}     // '-';
    }
    else {
        print "database:         (not found)\n";
    }
}

sub need_pkg {
    my $name = shift @ARGV or die "This command needs a package name.\n";
    my $pkg = $bp->get($name);
    die "Package '$name' not found.\n" unless $pkg;
    return $pkg;
}

sub cmd_info {
    my $p = need_pkg();
    printf "%-16s %s%s\n", 'Package:', $p->name,
        ($p->is_removed ? "  [REMOVED ".($p->removed_at//'')."]" : '');
    printf "%-16s %s\n", 'Version:', $p->current_version // '-';
    printf "%-16s %s\n", 'Summary:', $p->summary // '-';
    printf "%-16s %s\n", 'License:', $p->license // '-';
    printf "%-16s %s\n", 'Home:',    $p->home // '-';
    printf "%-16s %s\n", 'Doc URL:', $p->doc_url // '-' if $p->doc_url;
    printf "%-16s %s\n", 'noarch:',  $p->noarch if $p->noarch;
    printf "%-16s %s\n", 'Downloads:', $p->downloads if defined $p->downloads;
    my @ids = $p->identifiers;
    printf "%-16s %s\n", 'Identifiers:', join(', ', @ids) if @ids;
    printf "%-16s %s\n", 'Run deps:', scalar($p->dependencies('run'));
}

sub cmd_deps {
    my $p = need_pkg();
    my $kind = $opt{kind} || 'run';
    for my $d ($p->dependencies($kind)) {
        printf "%s%s\n", $d->{name},
            (defined $d->{constraint} ? " $d->{constraint}" : '');
    }
}

sub cmd_versions {
    my $p = need_pkg();
    print "$_\n" for $p->versions;
}

sub cmd_search {
    my $term = shift @ARGV or die "search needs a term.\n";
    print "$_\n" for $bp->search($term, include_removed => $opt{all});
}

sub cmd_rdeps {
    my $name = shift @ARGV or die "rdeps needs a package name.\n";
    print "$_\n" for $bp->reverse_dependencies(
        $name, kind => ($opt{kind} || 'run'), include_removed => $opt{all});
}

sub cmd_removed {
    print "$_\n" for $bp->removed;
}

sub cmd_list {
    print "$_\n" for $bp->list(include_removed => $opt{all});
}

sub cmd_stats {
    my %s = $bp->stats;
    printf "Database version: %s\n", $s{db_version} // '(unversioned)';
    printf "Total packages:   %d\n", $s{total};
    printf "Current:          %d\n", $s{current};
    printf "Removed:          %d\n", $s{removed};
    printf "noarch:           %d\n", $s{noarch};
    printf "Generated at:     %s\n", $s{generated_at}   // '-';
    printf "Recipes commit:   %s\n", $s{recipes_commit} // '-';
}
