#!/usr/bin/python
#encoding: utf8

import argparse
import collections
import sys

from plumper.sumo.plwnpwnsumo_file import MappingFileOperator
from plumper.sumo.plwnpwnsumo_map import PlwnPwnSumoMap

# Alias this for convenience
_R = PlwnPwnSumoMap.MANUALLY
if not isinstance(_R, unicode):
	_R = _R.decode('utf8')

class RReductor(MappingFileOperator):


	def __init__(self):
		MappingFileOperator.__init__(self)
		self._line_ids = None
		self._plwn_sumo_rels = None

	def __linefunc(self, plWN_str, sumo_str, sumo_rel):
		line_id = plWN_str, sumo_str
		self._line_ids.append((line_id, sumo_rel))

		if sumo_rel != _R:
			self._plwn_sumo_rels[line_id].add(sumo_rel)

	def reduce_R(self, mapping_result_file, out_fileobj=sys.stdout):
		self._line_ids = []
		self._plwn_sumo_rels = collections.defaultdict(set)

		self.read_mapping_file(
			mapping_result_file,
			(u'synset_str_plwn', u'pojecie_sumo', -1),
			self.__linefunc)

		# Expand header to add the output column
		self._header.append('plwn_sumo_rel_step1')

		for i in xrange(len(self._line_ids)):
			line_id, sumo_rel = self._line_ids[i]
			# If the sumo relation is known (not R)
			# or it is R, but we have no guesses
			# then just print it out as it is
			self._linebuffer[i].append(
				sumo_rel
				if sumo_rel != _R or line_id not in self._plwn_sumo_rels
				else u','.join(self._plwn_sumo_rels[line_id]))

		self.print_contents(out_fileobj)

def main(args=None):
	argp = argparse.ArgumentParser(
		description='Pierwszy krok automatycznego zmniejszania liczby R ' +
		'w wynikach rzutowania plWN -> SUMO. Wyniki są wypisywane na stdout')
	argp.add_argument('mapping_result_file',
		help='plik csv z wynikami rzutowania plWN -> SUMO')

	argv = argp.parse_args(args)

	rr = RReductor()
	rr.reduce_R(argv.mapping_result_file)

if __name__ == '__main__':
	main()
