#!/usr/bin/env perl
use v5.38;
use DBIx::Fast;

# Live connection monitor (MariaDB/MySQL). One-shot report plus an optional
# continuous mode, and a demonstration of the unified output layer: pass
# --json to emit machine-readable events instead of the text report.
#
# Usage:
#   perl -Ilib examples/monitor-connections.pl mariadb://root:test123@127.0.0.1:3307/dbix_test
#   perl -Ilib examples/monitor-connections.pl --json <dsn>
#   perl -Ilib examples/monitor-connections.pl --watch <dsn>   # refresh every 5s

my ($json, $watch);
while (@ARGV && $ARGV[0] =~ /^--/) {
    my $opt = shift @ARGV;
    $json  = 1 if $opt eq '--json';
    $watch = 1 if $opt eq '--watch';
}
# DSN from ARGV, falling back to the dev-test.sh environment.
my $dsn = shift(@ARGV)
       // $ENV{DBIX_FAST_TEST_MARIADB}
       // die "Usage: $0 [--json] [--watch] <dsn>   (or set DBIX_FAST_TEST_MARIADB)\n"
            . "  Example: $0 mariadb://root:test123\@127.0.0.1:3307/dbix_test\n";

my $db = DBIx::Fast->new(
    dsn => $dsn,
    $json ? (profile_output => 'json') : (),
);

if ($watch) {
    # Refresh every 5 seconds for one minute (Ctrl+C to stop earlier).
    $db->profiler->start_connection_monitor(5, 60);
}
else {
    $db->profiler->print_connection_monitor;
}
