#!/usr/bin/python

import argparse, os, readline, requests
from bs4 import BeautifulSoup

try:
	readline.read_history_file(os.path.expanduser('~/.wash.history'))
except IOError:
	pass

parser = argparse.ArgumentParser(description='Wolfram|Alpha interactive shell')
parser.add_argument('-v', '--verbose', action='store_true', help='Output XML for each response')

args = parser.parse_args()

def indent(text):
	return '\n'.join('    ' + x for x in text.split('\n'))

def clean(text):
	text = text.replace(u'\uf7d9', '=')
	return text

def wa_query(query):
	xml = requests.get(url, params=dict(input=query, appid=appid, format='plaintext')).content
	if args.verbose:
		print xml
	return BeautifulSoup(xml, 'html.parser')

url = 'http://api.wolframalpha.com/v2/query'
fn = os.path.expanduser('~/.wash.appid')
try:
	appid = file(fn).read()
	first_run = False
except:
	first_run = True
	print '\033[93m-- No Wolfram|Alpha app ID'
	print 'If you do not already have one, go to:'
	print '  https://developer.wolframalpha.com/portal/apisignup.html\033[0m'
	while True:
		appid = raw_input('Please enter your app ID: ').strip()
		bs = wa_query('Cody Brocious')
		print '\033[93mVerifying App ID...'
		if bs.queryresult['success'] == 'true' and bs.queryresult['error'] == 'false':
			print '\033[92mApp ID is correct\033[0m'
			with file(fn, 'w') as fp:
				fp.write(appid)
			break
		else:
			print '\033[91mApp ID is invalid\033[0m'

if first_run:
	print
	print '\033[92mWelcome to W|ASH\033[0m'
	print '\033[93mTo get started, simply type a query here as if you are on the Wolfram|Alpha site.'
	print 'For instance, try this: the 15th prime number * 20\033[0m'
	print

result = None

while True:
	try:
		query = raw_input('W|A> ').strip()
	except EOFError:
		print
		break
	except KeyboardInterrupt:
		print
		continue
	readline.write_history_file(os.path.expanduser('~/.wash.history'))
	if query == '':
		continue
	elif query == 'quit' or query == 'exit':
		print '\033[91mTo quit W|ASH, press Ctrl-D\033[0m'
		continue
	elif query == 'help':
		print '\033[1m\033[92mW|ASH Help\033[0m'
		print '\033[93m - Type a query to send it to Wolfram|Alpha'
		print ' - $$ in a query will be replaced by the previous result'
		print ' - Ctrl-D to quit\033[0m'
		print
		continue
	
	if '$$' in query:
		if result is not None:
			query = query.replace('$$', ' (%s) ' % result)
		else:
			print '\033[91m$$ in query with no previous result!\033[0m'
			print
			continue

	bs = wa_query(query)
	if bs.queryresult['success'] == 'true':
		for pod in bs.find_all('pod'):
			print '  \033[1m\033[92m%s\033[0m' % pod['title']
			numsubpods = int(pod['numsubpods'])
			for i, subpod in enumerate(pod.find_all('subpod')):
				if len(subpod.plaintext.contents):
					text = clean(indent('\n'.join(subpod.plaintext.contents)))
					print text

					if pod['title'] == 'Result':
						result = text
						if '  (' in result:
							result = result.split('  (', 1)[0]
					if i + 1 < numsubpods and numsubpods > 1 and '\n' in text:
						print
		if len(bs.find_all('pod', dict(scanner='Formula'))):
			print
			print '\033[91mThis appears to be an interactive formula.'
			print 'Results may be nonsensical.\033[0m'
	else:
		print '\033[91mQuery failed\033[0m'
		for tip in bs.find_all('tip'):
			print '\033[93m-', tip['text'], '\033[0m'
	print
