import socket

PORT = 8080
HOST = 'localhost'
TABLES_FILE = 'tables.txt'

def read_text_data(filename):
    with open(filename, 'r') as file:
        data = file.read()
    return data

def generate_html_table(data):
    lines = data.strip().split('\n')
    html = "<html><head><title>Table Data</title></head><body>"
    html += "<table border='1'><tr>"
    for header in lines[0].split(', '):
        html += f"<th>{header}</th>"
    html += "</tr>"
    for line in lines[1:]:
        html += "<tr>"
        for item in line.split(', '):
            html += f"<td>{item}</td>"
        html += "</tr>"
    html += "</table></body></html>"
    return html

def http_server():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
        server.bind((HOST, PORT))
        print(f"Server running on {HOST}:{PORT}")

        server.listen()

        while True:
            conn, addr = server.accept()
            print('Connected by', addr)

            request = conn.recv(1024).decode('utf-8')
            print('Request:', request)

            method, path, *_ = request.split()
            
            if method == 'GET':
                if path == '/':  # Отвечаем на все GET запросы
                    data = read_text_data(TABLES_FILE)
                    html_table = generate_html_table(data)
                    response = f'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n{html_table}'.encode()
                else:
                    response = b'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\nFile not found'

                conn.sendall(response)

if __name__ == '__main__':
    http_server()