#!/usr/bin/env perl

use strict;
use warnings;
use feature 'say';

use PPI;
use HPB::PPIx::Utils;

for my $file (@ARGV) {
	my $document = PPI::Document->new ($file);

	set_test_deep_import_version ($document, $file);

	$document->save ($file);
}

sub set_test_deep_import_version {
	my ($document, $file) = @_;

	return unless grep $_->content eq 'obj_isa', @{ $document->find ('PPI::Token::Word') };

	for my $include (@{ $document->find ('PPI::Statement::Include') // [] }) {
		next if $include->pragma;
		next unless $include->module eq 'Test::Deep';

		my $version = $include->module_version;
		if ($version && $version->literal < 0.111) {
			$version->previous_sibling->remove
				unless $version->previous_sibling->significant;
			$version->remove;
			$version = undef;
		}

		unless ($version) {
			my $insert_before = $include->schild(2);

			$insert_before->insert_before (PPI::Token::Whitespace->new (' '));
			$insert_before->insert_before (PPI::Token::Number::Version->new ('v0.111'));

			$include->insert_after (PPI::Token::Comment->new ('# 0.111 => obj_isa'));
			$include->insert_after (PPI::Token::Whitespace->new (' '));
		}
	}
}

__END__

for my $file (@ARGV) {
	my $document = CSI::Document->new (Perl => $file);

	$document->(
		find  { '::Statement::Include' },
		where { $_->module eq 'Test::Deep' },
		where { $_->module_version < v0.111 },
		apply { $_->module_version (v0.111) },
		apply { $_->statement_comment ('0.111 => obj_isa') },
	);

	$document->save if $document->modified;
}
