import socket
import re
from collections import defaultdict

answerfile = open('answers', 'a+')

sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('0.0.0.0', 8008))
sock.listen(10)

ip_count = defaultdict(lambda: defaultdict(int))

while True:
    cs, addr = sock.accept()
    try:
        answer = cs.recv(1024).decode('utf-8').strip()
    except:
        try:
            cs.close()
        except:
            continue
        continue

    if not re.match(r"^inputs/large_\d+\.input \d+$", answer):
        cs.close()
        continue

    f, a = answer.split()
    try:
        a_ = int(a)
        if a_ < 1 or a_ > 1000:
            cs.close()
            continue
    except:
        cs.close()
        continue
    ip = addr[0]

    if ip == '84.107.251.46':
        cs.send(b'charli xcx is duidelijk de betere charli\n')
        cs.close()
        continue

    ip_count[ip][f] += 1;
    if ip_count[ip][f] > 4:
        print('teveel keer zelfde bestand')
        cs.close()
        continue

    cs.send(b'Got answer: ' + answer.encode('utf-8') + b'\n')
    cs.close()

    print(f'Got answer from {addr[0]}: {answer}')
    answerfile.write(answer + '\n')
    answerfile.flush()
