package Mnemonics;

use strict;
use warnings;
use diagnostics;

use FindBin;
use lib "$FindBin::Bin/../Modules";
use Filters;

use feature 'say';

sub query {
    my ( $experiment, $experiment_dir, @filter_config_names ) = @_;

    my $filters =
      Filters::build_filter_clause( $experiment_dir, @filter_config_names );

    my $querystring = "SELECT
CASE
  WHEN o.disassemble IS NOT NULL AND SUBSTRING_INDEX(TRIM(o.disassemble), ' ', 1) REGEXP '^[a-zA-Z][a-zA-Z0-9 ]*\$'
  THEN SUBSTRING_INDEX(TRIM(o.disassemble), ' ', 1)
  ELSE NULL
END AS mnemonic,
COUNT(DISTINCT CONCAT(t.instr2, '_', t.data_physical_address)) AS count
FROM variant v
JOIN trace t ON v.id = t.variant_id
LEFT JOIN fspgroup g ON g.variant_id = t.variant_id AND g.instr2 = t.instr2 AND g.data_physical_address = t.data_physical_address
LEFT JOIN fsppilot p ON p.id = g.pilot_id
JOIN objdump o ON o.variant_id = v.id AND o.instr_address = t.instr2_absolute
WHERE v.variant = '$experiment'$filters
GROUP BY mnemonic
ORDER BY count DESC;";

    say $querystring;

    return $querystring;
}

sub args { return "--batch --raw"; }

sub filename {
    my @filter_config_names = grep { defined && length } @_;
    my $suffix =
      @filter_config_names ? "_" . join( "+", sort @filter_config_names ) : "";
    return "mnemonics${suffix}.csv";
}

sub postprocess { $_[0] =~ s/\t/,/g; }

1;
