#!/usr/bin/python
#
# Language Learner with No Name - LLNN
# V 4.0
# (c)2001-2013 M.J.London <llnn@knm.org.uk>

# TODO:
# DB error checking
# Better exception handling
# Actions

import os
import string
import random
import shelve
import adodb
from ircbot import SingleServerIRCBot
from irclib import nm_to_n, irc_lower

class LLNN(SingleServerIRCBot):
	def __init__(self, channel, nickname, server, port=6667, nspasswd=None, debug=0):
		SingleServerIRCBot.__init__(self, [(server, port)], nickname, "Language Learning Bot")
		self.channel = channel
		self.passwd = "password"
		self.nspasswd = nspasswd
		self.nickname = nickname
		self.endwordid = 0
		self.debuglevel = debug
		try:
			#Open DB
			print "Opening database"
			self.db = adodb.NewADOConnection('mysql')
			# Connect to host, username, password, database
			self.db.Connect('localhost','llnn','llnn','llnn')
		except:
			print "Error opening database"
		try:
			#Setup cache
			print "Setting up cache"
			self.endchars={}
			cursor=self.db.Execute("SELECT class, endchar FROM classes GROUP BY class")
			for row in cursor:
				self.endchars[row[1]]=row[0]
			self.defaultendchar = "."
			c = min(self.endchars.values())
			for char in self.endchars:
				if self.endchars[char] == c:
					self.defaultendchar = char
					break
			if self.is_debug(1): print "Available sentence end characters: ", self.endchars.keys()
			if self.is_debug(1): print "Default sentence end character: ", self.defaultendchar
			self.substrstart={}
			self.substrstartbyid={}
			self.substrend={}
			self.substrendbyid={}
			cursor=self.db.Execute("SELECT id, startchars, endchars FROM substrings")
			for row in cursor:
				self.substrstart[row[1]]=row[0]
				self.substrstartbyid[row[0]]=row[1]
				self.substrend[row[2]]=row[0]
				self.substrendbyid[row[0]]=row[2]
		except:
			print "Error reading stored data"	
			print 
		self.start()

	def __del__(self):
		self.conn.Close()

	def is_debug(self, level):
		# Is debug level level enabled?
		if (self.debuglevel & level) >0:
			return True
		else:
			return False
	
	def set_debug(self, level):
		self.debuglevel = level

	def get_version(self):
		return "LLNN Version 4.0 (c)2001-2013 M.London"

	def on_welcome(self, c, e):
		c.join(self.channel)

	def on_privmsg(self, c, e):
		print "<" + nm_to_n(e.source()) + "> [MSG]", e.arguments()[0]
		self.addressed(c, nm_to_n(e.source()), nm_to_n(e.source()), e.arguments()[0])

 	def on_privnotice(self, c, e):
 		print "[" + nm_to_n(e.source()) + "] [NOTICE]", e.arguments()[0]
 		if e.source() and e.source() == 'NickServ!NickServ@services.':
 			if irc_lower(e.arguments()[0]).find('identify') >= 0:
 				if self.nspasswd and self.nickname == self.connection.get_nickname():
 					print "Attempting to identify to NickServ..."
 					print "[" + self.connection.get_nickname() + "] identify " + self.nspasswd
 					c.privmsg(nm_to_n(e.source()),'identify %s' % self.nspasswd)

	def on_pubmsg(self, c, e):
		print "<" + nm_to_n(e.source()) + ">", e.arguments()[0]
		a = string.split(e.arguments()[0], ":", 1)
		if len(a) < 2:
			a = string.split(e.arguments()[0], ",", 1)
		if len(a) < 2:
			a = string.split(e.arguments()[0], " ", 1)
		if len(a) > 1 and irc_lower(a[0]) == irc_lower(self.connection.get_nickname()):
			self.addressed(c, e.target(), nm_to_n(e.source()), string.strip(a[1]))
		else:
			if not len(a)<1:
				self.process_line(e.arguments()[0])
		return

	def on_ctcp(self, c, e):
		if len(e.arguments()) > 1:
			if e.arguments()[0] == "ACTION":
				print "*" + nm_to_n(e.source()), e.arguments()[1]
				self.process_line('\001ACTION ' + e.arguments()[1] + '\001')
			else:
				print "[CTCP", e.arguments()[0] + "]", "<" + nm_to_n(e.source()) + ">", e.arguments()[1]
		else:
			print "[CTCP", e.arguments()[0] + "]", "<" + nm_to_n(e.source()) + ">"
		if e.arguments()[0] == "PING":
			if len(e.arguments()) > 1:
				response = e.arguments()[1]
			else:
				response = ""
			c.ctcp_reply(nm_to_n(e.source()), e.arguments()[0]+' '+response)
		elif e.arguments()[0] == "VERSION":
			print "[CTCP Reply]", self.get_version()
			c.ctcp_reply(nm_to_n(e.source()), e.arguments()[0]+' '+self.get_version());

	def on_invite(self, c, e):
		print nm_to_n(e.source()),"invited me to",e.arguments()[0]
		print "Joining",e.arguments()[0]
		c.join(e.arguments()[0])

	def command(self, nick, cmdstring):
		c = self.connection
		cmd = string.split(cmdstring)
		print "Command from",nick,":",cmd
		if cmd[0] == "die":
			self.save_data()
			self.die()
		elif cmd[0] == "join" and len(cmd) > 1:
			print "Joining",cmd[1]
			if len(cmd) > 2:
				c.join(cmd[1], cmd[2])
			else:
				c.join(cmd[1])
		elif cmd[0] == "part" and len(cmd) > 1:
			print "Leaving",cmd[1]
			c.part(cmd[1])
	
	def addressed(self, c, source, nick, message):
#		print "Addressed by",nick,":",message
		p = string.split(message)
		if len(p)<1:
			return
		if p[0] == self.passwd and len(p) > 1:
			self.command(nick, string.join(p[1:]))
		elif irc_lower(p[0]) == "speak":
			c.privmsg(source, self.create_sentence())
		elif irc_lower(p[0]) == "stats":
			#out = "I know "+`len(self.words)`+" words, "+`len(self.canstart)`+" can start a sentence and "+`len(self.canend)`+" can end a sentence"
			out = "Statistics not currently supported"
			c.privmsg(source, out)
		elif nm_to_n(source) == nick:
			self.process_line(message)
			c.privmsg(source, self.create_sentence())
		else:
			self.process_line(message)
			c.privmsg(source, self.create_sentence())

	def process_line(self, line, issubstring=False):
		if self.is_debug(1): print "Processing line:",line
		parsed = []
		sentence = []
		words = string.split(line)
		if len(words)<1:
			return
		# First handle special case for substrings
		substrclass = self.is_substringstart(words[0])
		if self.is_debug(2) and substrclass: print "First word is substring start"
		if substrclass and self.is_substringend(words[-1],substrclass):
			if self.is_debug(2): print "Last word is substring end - strip marker characters: start={0} end={1}".format(self.substrstartbyid[substrclass],self.substrendbyid[substrclass])
			# Strip substring start chars
			words[0]=self.substrstartbyid[substrclass].join(words[0].split(self.substrstartbyid[substrclass])[1:])
			#words[0]=words[0][1:]
			# Strip substring end chars
			# This is a nasty hack (entirely IRC specific), but it saves a major rewrite:
			# - don't strip ^A as a substring end character - this allows it to be treated as a sentence end character
			# - this means that actions are treated as their own sentence class
			if(self.substrendbyid[substrclass]!=chr(1)):
				words[-1]=self.substrstartbyid[substrclass].join(words[-1].split(self.substrendbyid[substrclass])[:-1])
			#words[-1]=words[-1][:-1]
			if self.is_debug(2): print "First and last words are now:",words[0],words[-1]
			# Increment startword weight for this substring type if this isn't a recursive call
			if not issubstring:
				if self.is_endword(words[-1]):
					endchar = words[-1][-1:]
				else:
					endchar = self.defaultendchar
				self.addstartword(substrclass,endchar)
		# Identify sentences
		w = 0
		endpos = 0
		while w < len(words):
			word = words[w]
			substrstart = self.is_substringstart(word)
			if substrstart:
				if self.is_debug(2): print "Substring start found at position:",w
				endpos = self.find_substringend(words[w:], substrstart)
				if self.is_debug(2): print "Substring endpos returned as position:",w
				if endpos == 0:
					sentence.append(word)
					w=w+1
				elif endpos>0:
					endchar = words[w+endpos-1][-1:]
					self.process_line(' '.join(words[w:w+endpos]),True)
					sentence.append(word)
					w=w+endpos
			elif self.is_endword(word):
				endchar = word[-1:]
				word = word[:-1]
				sentence.append(word)
				self.process_sentence(self.parse_sentence(sentence,endchar),endchar,substrclass)
				sentence = []
				w=w+1
			else:
				sentence.append(word)
				w=w+1
		# If the line doesn't end with an endchar, sentence will not be empty
		# Process as if it ended with the detault endchar
		if len(sentence)>0:
			self.process_sentence(self.parse_sentence(sentence,self.defaultendchar),self.defaultendchar,substrclass)

	def is_substringstart(self,word):
		# Check for start of substring
		# Return substringtype or False if not a substring
		for chars in self.substrstart:
			charsnowhite = chars.strip(' ')
			if word[:len(chars)] == chars:
				return self.substrstart[chars]
			elif word[:len(charsnowhite)] == charsnowhite:
				return self.substrstart[chars]
		return False

	def is_substringend(self,word,substringtype):
		# Check for end of substring of specified type
		if self.is_debug(2): print "Is substring end:", word, substringtype
		for c in self.substrend:
			if self.substrend[c] == substringtype:
				chars = c	
				break
		if self.is_debug(2): print "Substring end chars:", chars
		if word[-len(chars):] == chars:
			if self.is_debug(2): print "Substring end"
			return True
		else:
			if self.is_debug(2): print "Not substring end"
			return False

	def find_substringend(self,words,substringtype):
		# Look for substring end and return string position if found
		# Return False if not found
		depth=0 # first word contains substring start char
		if self.is_debug(2): print "Find substring end for:", words, substringtype
		for w in range(len(words)):
			word = words[w]
			if self.is_debug(2): print "Word:",word
			if self.is_substringstart(word) == substringtype:
				depth = depth + 1
				if self.is_debug(2): print "New depth:",depth
			if self.is_substringend(word,substringtype):
				if depth > 1:
					depth = depth -1
					if self.is_debug(2): print "New depth:",depth
				else:
					if self.is_debug(2): print "Found end at:", w
					return w+1 # 0 would be no end found
		if self.is_debug(2): print "No end found"
		return False 

	def is_endword(self,word):
		# Check last character is an endchar
		if self.endchars.has_key(word[-1:]):
			return True
		else:
			return False

	def parse_sentence(self, sentence, endchar):
		# Parse words into wordids
		if self.is_debug(1): print "Parsing :", sentence, endchar
		parsed = []
		for word in sentence:
			s = self.is_substringstart(word)
			if s:
				parsed.append(s)
			else:
				parsed.append(self.getwordid(word,endchar))
		return parsed

	def process_sentence(self, parsed, endchar, substring=False):
		# Process the parsed sentence
		# Endchar tells us the sentence class, parsed contains the wordids
		# Substring contains the substring class if this is a substring
		if self.is_debug(1): print "Processing :", parsed, endchar, substring
		if substring:
			self.addlink(substring,parsed[0])
		else:
			self.addstartword(parsed[0],endchar)
		for w in range(len(parsed)-1):
			self.addlink(parsed[w],parsed[w+1])
		self.addlink(parsed[-1],self.endwordid)

	def addstartword(self,word,endchar):
		if self.is_debug(2): print "Updating startword count for wordid:", word
		cursor = self.db.Execute('UPDATE classes SET weight=weight+1 WHERE startword=%s AND endchar=%s',(word,endchar))
		if cursor.RecordCount() < 1:
			if self.is_debug(1): print "Entry missing from DB - adding with weight=1"
			cursor = self.db.Execute('INSERT INTO classes (class, startword, weight, endchar) VALUES (%s,%s,1,%s)', (self.getsentenceclass(endchar), word, endchar))

	def addlink(self,word,nextword):
		# Update DB adding entry if missing, incrementing weight if it does
		# UPDATE, if no rows affected, INSERT
		if self.is_debug(1): print "Updating link count for ", word, " to ",  nextword 
		cursor = self.db.Execute('UPDATE links SET weight=weight+1 WHERE word=' + str(word) + " AND nextword=" + str(nextword))
		if cursor.RecordCount() < 1:
			if self.is_debug(1): print "Entry missing from DB - adding with weight=1"
			cursor = self.db.Execute('INSERT INTO links (word, nextword, weight) VALUES (' + str(word) + ", " + str(nextword)+ ", 1)")

	def getsentenceclass(self, endchar):
		if self.is_debug(2): print "Get sentence class for endchar: " + endchar
		if endchar in self.endchars:
			return self.endchars[endchar]
		else:
			return None

	def getwordid(self, word, endchar):
		sentenceclass = self.getsentenceclass(endchar)
		if self.is_debug(2): print "Lookup word: ", word, " with sentence class: ", sentenceclass
		cursor = self.db.Execute('SELECT id FROM words WHERE word=%s AND class=%s',(word,sentenceclass))
		if cursor == None or cursor.RecordCount() == 0:
			if self.is_debug(1): print "Adding word: ", word, " with sentence class: ", sentenceclass
			cursor = self.db.Execute('INSERT INTO words(word,class) VALUES (%s, %s)',(word, sentenceclass))
			cursor = self.db.Execute('SELECT id FROM words WHERE word=%s AND class=%s',(word,sentenceclass))
		if cursor == None or cursor.RecordCount() == 0:
			return 0
		return cursor.fields[0]

	def getword(self,wordid):
		if self.is_debug(4): print "Lookup word: ", wordid
		cursor = self.db.Execute('SELECT word FROM words WHERE id=' + str(wordid))
		if cursor == None or cursor.RecordCount() == 0:
			print "Word lookup failed. Word ID =",wordid
			return ""
		return cursor.fields[0]

	def getnextword(self,word):
		# Build list of links, expanding weights
		cursor = self.db.Execute("SELECT nextword, weight FROM links WHERE word=" + str(word))
		links = []
		if cursor == None or cursor.RecordCount() == 0:
			return 0
		for row in cursor:
			for i in range(row[1]):
				links.append(row[0])
		return random.choice(links)

	def create_sentence(self):
		sentence = []
		# Build list of possible start words, expanding weights
		startwords=[]
		cursor = self.db.Execute("SELECT startword, weight, endchar FROM classes")
		if cursor == None or cursor.RecordCount() == 0:
			return ""
		for row in cursor:
			for i in range(row[1]):
				startwords.append((row[0],row[2]))
		if self.is_debug(4): print "Starting words:",startwords
		# Pick random start word
		w = random.choice(startwords)
		word = w[0]
		endchar = w[1]
		while word != 0:
			if word > 0 and word < 100:
				# Insert substring into sentence
				# Get substring start and end characters
				s = self.substrstartbyid[word]
				s = s + self.create_sentence()
				if s.endswith('.'): s = s[:-1]
				s = s + self.substrendbyid[word]
				sentence.append(s)
			else:
				sentence.append(self.getword(word))
			word = self.getnextword(word)
		# Special case for actions - no endchar
		if sentence[-1] != '' and sentence[-1][-1] == "\001":
			endchar = ""
		return ' '.join(sentence) + endchar

	def save_data(self):
		# If cache has been modified, but DB has not, flush changes to DB
		# At present nothing modifies any cached data
		return True


def main():
	import sys
	if len(sys.argv) == 1:
		server = "localhost"
		port = 6667
		channel = "#llnn"
		nick = "llnn"
		nspasswd = None
	else:
		if len(sys.argv) < 4 or len(sys.argv) > 5:
			print "Usage: ",sys.argv[0]," server[:port] channel nick nickservpassword"
			sys.exit(1)
	
		s = string.split(sys.argv[1], ":", 1)
		server = s[0]
		if len(s) == 2:
			try:
				port = int(s[1])
			except ValueError:
				print "Error: Bad port"
				sys.exit(1)
		else:
			port = 6667
		channel = sys.argv[2]
		nick = sys.argv[3]
 		if len(sys.argv) > 4:
 			nspasswd = sys.argv[4]
 		else:
 			nspasswd = None

	llnnbot = LLNN(channel, nick, server, port, nspasswd,3)
	llnnbot.start()


if __name__ == "__main__":
	main()
