#   pyRCV2: Preferential vote counting
#   Copyright © 2020–2021  Lee Yingtong Li (RunasSudo)
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <https://www.gnu.org/licenses/>.

from pytest_steps import test_steps

import pyRCV2.blt
import pyRCV2.numbers
from pyRCV2.method.meek import MeekSTVCounter
from pyRCV2.model import CandidateState
import tests.util

import csv

def isclose(a, b):
	# Allow discrepancy of ~0.01
	diff = a - b
	if diff < pyRCV2.numbers.Num('0.014') and diff > pyRCV2.numbers.Num('-0.014'):
		return True
	return False

# Read model CSV

with open('tests/data/ers97_meekm.csv', 'r', newline='') as f:
	reader = csv.reader(f)
	data = [x for x in reader]

candidates = [data[i][0] for i in range(2, len(data) - 2)]

@test_steps(*['Stage {}'.format(data[0][i]) for i in range(1, len(data[0]), 2)])
def test_ers97_meekm_py():
	"""Compare count of ers97.blt with model result produced by Hill et al. reference implementation"""
	
	pyRCV2.numbers.set_numclass(pyRCV2.numbers.FixedGuarded)
	pyRCV2.numbers.set_dps(4)
	
	with open('tests/data/ers97.blt', 'r') as f:
		election = pyRCV2.blt.readBLT(f.read())
	
	assert len(election.candidates) == len(candidates)
	
	counter = MeekSTVCounter(election, {
		'quota': 'droop_exact',
		'quota_criterion': 'gt',
		'quota_mode': 'progressive',
		'ties': []
	})
	result = counter.reset()
	
	for i in range(1, len(data[0]), 2):
		stage = int(data[0][i])
		
		while len(counter.step_results) < stage:
			result = counter.step()
		
		comment = data[1][i]
		assert result.comment == comment, 'Failed to verify comment'
		
		for j, cand in enumerate(candidates):
			votes = pyRCV2.numbers.Num(data[j + 2][i])
			cc = next(cc for c, cc in result.candidates.items() if c.name == cand)
			assert isclose(cc.votes, votes), 'Failed to verify candidate "{}" votes, got {} expected {}'.format(cand, cc.votes.pp(2), votes.pp(2))
			
			state = data[j + 2][i + 1] if len(data[j + 2]) > (i + 1) else ''
			accept = {'': CandidateState.HOPEFUL, 'EL': CandidateState.ELECTED, 'EX': CandidateState.EXCLUDED}
			assert cc.state == accept[state], 'Failed to verify candidate "{}" state'.format(cand)
		
		# NB: Ignore exhausted votes
		
		quota = pyRCV2.numbers.Num(data[len(candidates) + 3][i])
		assert isclose(result.quota, quota), 'Failed to verify quota, got {} expected {}'.format(result.quota.pp(2), quota.pp(2))
		
		yield 'Stage {}'.format(stage)
