use Test2::V0;
use Data::Dumper;
use Try::Tiny;
use URI;
use URI::Fast qw(uri);

sub new_uri {
  my $uri = uri $_[0];
  return {
    scheme => scalar $uri->scheme,
    auth   => scalar $uri->auth,
    path   => scalar $uri->path,
    query  => scalar $uri->query,
    frag   => scalar $uri->frag,
    host   => scalar $uri->host,
    port   => scalar $uri->port,
  };
}

sub old_uri {
  my $uri  = URI->new($_[0]);
  my $host = '';
  my $port = '';

  if ($uri->can('host')) {
    $host = $uri->host;

    if ($uri->authority =~ /:\d+/) {
      $port = $uri->port;
    }
  }

  return {
    scheme => scalar $uri->scheme,
    auth   => scalar $uri->authority,
    path   => scalar $uri->path,
    query  => scalar $uri->query    // '', # URI returns undef whereas URI::Fast returns ''
    frag   => scalar $uri->fragment // '', # URI returns undef whereas URI::Fast returns ''
    host   => scalar $host,
    port   => scalar $port,
  };
}

sub run_test {
  open my $fh, '<', '/Users/sysread/Downloads/referers2.txt' or die $!;
  my $max = 5000;
  my $i = 0;

  while (my $line = <$fh>) {
    chomp $line;
    $line =~ s/[^-_?&#\@:#\.\/%a-zA-Z0-9]//g;

    my $new = new_uri $line;
    my $old = old_uri $line;
    is $new, $old, $line;

    last if ++$i >= $max;
  }

  diag "tested $i uris";

  close $fh;

  done_testing;
}

run_test();
