package LIMS::Local::DevelCycle;

use strict;
use warnings;

use IO::All;
use Path::Tiny;
use Devel::Cycle;
use FindBin qw($Bin); # warn $Bin;
use Capture::Tiny ':all';
use Data::Printer alias => 'p';

{ # patched _get_type sub to prevent "Unhandled type: REGEXP" warning:
    # https://rt.cpan.org/Public/Bug/Display.html?id=56681
    no warnings 'redefine';
    sub Devel::Cycle::_get_type {
        my $thingy = shift; # p $thingy; # very large output!!
        return unless ref $thingy;
#       return 'SCALAR' if UNIVERSAL::isa($thingy,'SCALAR') || UNIVERSAL::isa($thingy,'REF');
        # https://rt.cpan.org/Public/Bug/Display.html?id=56681 (also added GLOB):
        return 'SCALAR' if grep UNIVERSAL::isa($thingy, $_),
            qw(SCALAR REF REGEXP GLOB);
        return 'ARRAY'  if UNIVERSAL::isa($thingy,'ARRAY');
        return 'HASH'   if UNIVERSAL::isa($thingy,'HASH');
        return 'CODE'   if UNIVERSAL::isa($thingy,'CODE');
        undef;
    }
}

sub find {
    my $thing = shift;

    my $captured = capture_merged { find_cycle($thing) }; # warn $captured;

    if ($captured) {
        # return var if not fastcgi, will die if defined value:
        return $captured if grep $ENV{$_}, qw/DEVEL_SERVER HARNESS_ACTIVE/;

        my $logfile = path($Bin, '..', 'logs', 'devel_cycle.log')->realpath; # warn $logfile;
        io($logfile)->append($captured);
    }
    return 0; # don't die;
}

# exit 0;

1;
