package TAP::Harness::IgnoreNonessentialDzilAutogeneratedTests;

use warnings;
use strict;

use base 'TAP::Harness';
use File::Spec;
use IPC::Open2 'open2';

my $frivolous_test_map = {
# Test based on the extremely dep-heavy, *prone to failures* Test::CheckDeps
#
  't/00-check-deps.t' => [
    qr|^\Q# this test was generated with Dist::Zilla::Plugin::Test::CheckDeps|m,

    # older non-annotated versions
    qr|use \s+ Test::CheckDeps .*? ^\Qcheck_dependencies('suggests')\E .*? \QBAIL_OUT("Missing dependencies") if !Test::More->builder->is_passing|smx,
  ],

# "does everything compile" tests are useless by definition - this is what the
# rest of the test suite is for
#
  't/00-compile.t' => [
    qr|^\Q# this test was generated with Dist::Zilla::Plugin::Test::Compile|m,
  ],
};

sub aggregate_tests {
  my ($self, $aggregate, @all_tests) = @_;

  my ($run_tests, $skip_tests);

  TESTFILE:
  for (@all_tests) {
    my $fn = File::Spec::Unix->catpath( File::Spec->splitpath( $_ ) );

    if (my $REs = $frivolous_test_map->{$fn}) {
      my $slurptest = do { local (@ARGV, $/) = $fn; <> };
      $slurptest =~ $_ and push @$skip_tests, $fn and next TESTFILE for @$REs;
    }

    push @$run_tests, $fn;
  }

  if ($skip_tests) {

    for (@$skip_tests) {

      my $pid = open2(File::Spec->devnull, undef, $^X, qw(-I blib -I arch/lib), $_ )
        or die "Sub-proc failed: $!";
      waitpid ($pid, 0);

      $_ .= "[would NOT have passed: $?]" if $?;
    }

    print STDERR "=== Skipping nonessential autogenerated tests: @$skip_tests\n";
  }

  return $self->SUPER::aggregate_tests($aggregate, @$run_tests);
}

1;
