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

import argparse
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 ErrorFilter(MappingFileOperator):

	def __init__(self):
		MappingFileOperator.__init__(self)
		self._line_ids = None
		self._error_ids = None
		self._rel_mappings = None

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

		if line_id not in self._error_ids:
			# The comma means that there are multiple relations in one line
			# Instant error
			if u',' in sumo_rel:
				self._error_ids.add(line_id)
				return

			# Ignore relations marked for manual evaluation
			if sumo_rel == _R:
				return

			if line_id in self._rel_mappings:
				# If there was a mapping, but the one in the current line
				# is different, then it's an error
				if self._rel_mappings[line_id] != sumo_rel:
					self._error_ids.add(line_id)

				return

			# Add the mapping if there was none
			self._rel_mappings[line_id] = sumo_rel

	def filter_errors(self, mapping_result_file, out_fileobj=sys.stdout):
		self._line_ids = []
		self._error_ids = set()
		self._rel_mappings = {}

		self.read_mapping_file(
			mapping_result_file,
			# -1: take the last index, it should contain either the auto-mapped
			# relation, or the one supplied by rreductor
			(u'synset_str_plwn', u'pojecie_sumo', -1),
			self.__linefunc)

		self._print_header(out_fileobj)

		for i in xrange(len(self._line_ids)):
			if self._line_ids[i] in self._error_ids:
				self._print_line(i, out_fileobj)

def main(args=None):
	argp = argparse.ArgumentParser(
		description='Wypisuje "błędne" mapowania z pliku wejściowego, ' +
		'to znaczy takie, w których dla danego mapowania przypisano ' +
		'więcej niż jedną relację SUMO')
	argp.add_argument('mapping_result_file',
		help='plik csv z wynikami rzutowania plWN -> SUMO')

	argv = argp.parse_args(args)

	ef = ErrorFilter()
	ef.filter_errors(argv.mapping_result_file)

if __name__ == '__main__':
	main()
