import re
good_chars = 'abcdefghijklmnopqrstuvwxyz0123456789_- ,.()'
word_chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
stopwords = [ 'stop', 'the', 'to', 'and', 'a', 'in', 'it', 'is', 'i', 'that', 'had', 'on', 'for', 'were', 'was']

regexes = [
	(r"\w_\w", 'It looks like you are using the character "_" to separate words in tags. Use spaces instead.', 0.9),
	(r"\W-\w", 'It looks like you are using the "-" character to exclude tags. Put them into the "negative prompt" instead.', 0.9),
	(r"^.{,60}$", 'Your prompt is very short. You will probably get a bad image.', 0.8),
	(r"\b(stalin|hitler|nazi|nigger|waluigi|luigi|toilet)\b", 'Seriously?', 0.01),
	(r"\b(loli|shota|cub|young|age difference|preteen|underage|child|teen)\b", 'Trying to generate cub art will probably make you banned. I warned you.', 0.001),
	(r"\b(scat|poop|shit|piss|urine|pooping|rape)\b", 'Some of the tags you sent will be ignored because they were also blacklisted on e621.', 0.75),
	(r"\({3,}", 'No need to use that many (((parenthesis))). That will give you a worse image.', 0.9),
	(r"\[{3,}", 'Square [braces] will reduce the enphasis on a tag.', 1.0),
	(r"\W#", 'There is no need to put # in front of tags. That\'ll worsen the quality of the image', 0.9),
	(r"[👎👍🌀🌱💎]", "If you copy prompts from the channel, at least copy <strong>only</strong> the prompt.", 0.001)
]

tags = {}
with open('yiffy_tags.csv') as f:
	while 1:
		line = f.readline()
		if not line: break
		
		tag, value = line.strip().rsplit(',', 1)
		
		if value == 'count': continue		
		tags[tag] = int(value)		
sorted_by_size = sorted(tags.keys(), key=lambda x: len(x), reverse=True)

def judge(prompt):

	prompt = ' '+prompt.lower().replace("\n", ' ')+' '
	quality = 1.0
	comments = []

	found_tags = {}
	for tag in sorted_by_size:
		pos = prompt.find(tag)
		if pos == -1: continue
		if prompt[pos-1] in word_chars: continue
		if prompt[pos+len(tag)] in word_chars: continue
		
		found_tags[tag] = tags[tag]

	if len(found_tags) == 0:
		quality *= 0.65
		comments.append(f"Your prompt doesn't even contain one tag from e621.")
	elif len(found_tags) < 6:
		quality *= 0.8
		comments.append(f"Found only {len(found_tags)} tags in your prompt. The AI knows ~{int(sum(found_tags.values())/len(found_tags))} images from e621 with these tags.")
	else:	
		comments.append(f"Found {len(found_tags)} tags in your prompt. The AI knows ~{int(sum(found_tags.values())/len(found_tags))} images from e621 with these tags.")
		

	for pattern, comment, value in regexes:
		match = re.search(pattern, prompt)
		if match:
			quality *= value
			comments.append(comment)

	if quality < 1:
		comments.append(f"Because of these issues, you will consume {(1/quality):.2f}x the amount of usual cycles.")

	return comments, quality
