#!/usr/bin/perl

use strict;
use warnings;
use utf8;

use File::Basename;

BEGIN{
  my $GETAROOT = "/usr/local/geta";
  my $LIB = $GETAROOT . "/ext/wam";
  unshift(@INC, "$LIB", "$LIB/blib/lib", "$LIB/blib/arch");
};

use wam ('WAM_ROW', 'WAM_COL');

#引数１  検索対象WAMハンドルショートネーム
my $handle = shift @ARGV or help();
#引数２  検索結果取得件数
my $max = shift @ARGV;
#引数３  検索結果取得開始件数（検索結果の先頭からこの数未満の件数を無視）
my $start = shift @ARGV;
# 形態素分析スクリプトパス
my $ma  = dirname($0) . '/mecab.sh';

my $GETAROOT = "/usr/local/geta";
&wam::init ($GETAROOT) == 0 or die "$0 ERROR! cannot initialize WAM:$!, stopped";
(my $w = &wam::open($handle)) != 0 or die "$0 ERROR! cannot open:$!, stopped";

my $text = '';
my $articles = [];
my $words = [];
while (my $line = <STDIN>) {
  chomp($line);
  if (substr($line, 0, 3) eq '[t]') {
    $text .= substr($line, 3);
  } elsif (substr($line, 0, 3) eq '[w]') {
    $text .= substr($line, 3);
  } elsif (substr($line, 0, 3) eq '[a]') {
    my $row_id = &wam::name2id($w, WAM_ROW, substr($line, 3));
    if ($row_id) {
      my %row = ("name" => substr($line, 3), "id" => $row_id, "TF" => 0, "TF_d" => 1, "weight" => 0);
      push (@{$articles}, \%row);
    }
  }
}

if ($text) {
  my $rq = &wam::wstem($text, $w, WAM_COL, $ma);
  for (my $i = 0; $i < @$rq; $i++) {
    push (@{$words}, $rq->[$i] );
  }
}
if (@$articles) {
  my $rw = &wam::wsh($articles, $w, WAM_ROW, &wam::WT_SMART, 50, 0, $w);
  if (@$rw) {
    for (my $i = 0; $i < @$rw; $i++) {
      push (@{$words}, $rw->[$i] );
    }
  }
}

if (@$words) {
  if ($max < 1) {$max = 10;}
  if ($start < 1) {$start = 1;}
  $max = $max + $start - 1;

  my $rd = &wam::wsh($words, $w, WAM_COL, &wam::WT_SMART, $max, 0, $w);

  my $attr = "dataroot";
  my $titles = &wam::ci_value($handle, $attr) . $handle . ".ttl";

  my $rd_cnt = &wam::get_last_nd();
  printf "[C]\t%s\n", $rd_cnt;

  if (@$rd) {
    for (my $i = $start-1; $i < @$rd; $i++) {
      printf "[A]\t%s\t%s\t%s\n", $rd->[$i]{"name"}, $rd->[$i]{"weight"}, &wam::getaux($titles, $rd->[$i]{"id"});
    }

    my $rd2 = &wam::wsh($words, $w, WAM_COL, &wam::WT_SMART, 30, 0, $w);
    my $rc = &wam::wsh($rd2, $w, WAM_ROW, &wam::WT_SMART, 30, 0, $w);
    if (@$rc) {
      for (my $i = 0; $i < @$rc; $i++) {
        printf "[W]\t%s\n", $rc->[$i]{"name"};
      }
    }
  }
} else {
  print "[C]\t0\n";
}

sub help {
	die "$0 wam_handle_name max_results first_result\n";
}
