#!/usr/bin/env raku
use GTM::ToolFinder;
use JSON::Fast;

#| Search the OneGTMLab GTM tool directory (free API, no key).
sub MAIN(
    *@query,                   #= search words
    Str :$kind,                #= tool, category, comparison or glossary
    Str :$category,            #= category slug
    Int :$limit = 10,          #= 1 to 100
    Bool :$categories,         #= list the categories
    Str :$get,                 #= show one entry by id
    Bool :$json,               #= print raw JSON
) {
    my $c = GTM::ToolFinder.new;
    CATCH { default { note "gtm-tool-finder: {.message}"; exit 2 } }
    if $categories {
        my @c = $c.categories;
        $json ?? say to-json(@c) !! @c.map({ say sprintf("%-22s %3s tools  %s", .<slug>, .<tool_count> // '', .<url>) });
        exit 0;
    }
    if $get.defined {
        my %e = $c.get-entry($get);
        $json ?? say to-json(%e) !! say $c.format-entry(%e);
        exit 0;
    }
    my ($entries, $total) = $c.search(q => @query.join(' '), :$kind, :$category, :$limit);
    if $json { say to-json(%(:$total, data => $entries.list)) }
    else { .say for $entries.map({ $c.format-entry($_) }); note "{$entries.elems} of $total" }
    exit($entries.elems ?? 0 !! 1);
}
