#!/usr/bin/env python

"""
A tool which checks that a target SpiNNaker machine's wiring matches the
specifications generated by SpiNNer.
"""

import sys

import argparse

from spinner.utils import folded_torus

from spinner import transforms
from spinner import plan
from spinner import probe

from spinner.scripts import arguments

from rig.machine_control import BMPController


def main(args=None):
	parser = argparse.ArgumentParser(
		description="Validate the wiring of a SpiNNaker system.")
	arguments.add_version_args(parser)
	
	parser.add_argument("--verbose", "-v", action="store_true", default=False,
	                    help="list all incorrect and missing wires")
	
	arguments.add_topology_args(parser)
	arguments.add_cabinet_args(parser)
	arguments.add_bmp_args(parser)
	
	# Process command-line arguments
	args = parser.parse_args(args)
	(w, h), transformation, uncrinkle_direction, folds =\
		arguments.get_topology_from_args(parser, args)
	
	cabinet, num_frames = arguments.get_cabinets_from_args(parser, args)
	
	bmp_ips = arguments.get_bmps_from_args(parser, args,
	                                       cabinet.num_cabinets,
	                                       num_frames)
	
	if len(bmp_ips) == 0:
		parser.error("BMP host names must be provided for every frame.")
	
	# Generate folded system
	hex_boards, folded_boards = folded_torus(w, h,
	                                         transformation,
	                                         uncrinkle_direction,
	                                         folds)
	
	# Divide into cabinets
	cabinetised_boards = transforms.cabinetise(folded_boards,
	                                           cabinet.num_cabinets,
	                                           num_frames,
	                                           cabinet.boards_per_frame)
	cabinetised_boards = transforms.remove_gaps(cabinetised_boards)
	
	# Generate list of wires
	wires = plan.enumerate_wires(cabinetised_boards)
	
	# Set up the wiring probe
	bmp_controller = BMPController(bmp_ips)
	if cabinet.num_cabinets == 1 and num_frames == 1:
		num_boards = 3 * w * h
	else:
		num_boards = cabinet.boards_per_frame
	wiring_probe = probe.WiringProbe(bmp_controller,
	                                 cabinet.num_cabinets,
	                                 num_frames,
	                                 num_boards)
	
	
	# Check for the presence of every wire
	missing = []
	b2c = dict(cabinetised_boards)
	for ((src_board, src_direction), (dst_board, dst_direction)) in wires:
		src = tuple(list(b2c[src_board]) + [src_direction])
		dst = tuple(list(b2c[dst_board]) + [dst_direction])
		actual_dst = wiring_probe.get_link_target(*src)
		actual_src = wiring_probe.get_link_target(*dst)
		
		if actual_dst != dst or actual_src != src:
			missing.append((src, dst))
	
	if missing:
		sys.stderr.write("{} wires missing or erroneously connected.\n".format(
			len(missing), len(wires)))
		
		if args.verbose:
			for src, dst in missing:
				print("C:{} F:{} B:{} {} <--> C:{} F:{} B:{} {}".format(
					src[0], src[1], src[2], src[3].name.replace("_", " "),
					dst[0], dst[1], dst[2], dst[3].name.replace("_", " ")))
		else:
			print("Add --verbose for a complete list.")
		
		return -1
	else:
		sys.stderr.write("All {} wires correctly connected.\n".format(len(wires)))
		return 0


if __name__=="__main__":  # pragma: no cover
	import sys
	sys.exit(main())
