# Practical 5 – Timestamp Replay Detection: Server
import socket
from datetime import datetime, timedelta, timezone
from p5_networkSec_auth import authenticate_user, init_db

init_db()
last_time = None
window = timedelta(seconds=30)

with socket.socket() as server:
    server.bind(("127.0.0.1", 9999))
    server.listen(1)
    print("Server listening on port 9999")

    conn, addr = server.accept()
    with conn:
        print("Connected:", addr)

        username, password = conn.recv(1024).decode().split("|", 1)

        if authenticate_user(username, password):
            conn.sendall(b"AUTH_OK")
            print("Authenticated:", username)

            while data := conn.recv(1024).decode():
                try:
                    msg, t = data.split("||", 1)
                    msg_time = datetime.strptime(
                        t, "%Y-%m-%d %H:%M:%S.%f"
                    ).replace(tzinfo=timezone.utc)

                    now = datetime.now(timezone.utc)

                    if abs(now - msg_time) <= window and (
                        last_time is None or msg_time > last_time
                    ):
                        last_time = msg_time
                        reply = f"Valid message: {msg}"
                        print("[ACCEPTED]", msg)
                    else:
                        reply = "Old or invalid timestamp"
                        print("[REPLAY DETECTED]", msg)

                except ValueError:
                    reply = "Invalid message format"
                    print("[INVALID MESSAGE]")

                conn.sendall(reply.encode())
        else:
            conn.sendall(b"AUTH_FAILED")
            print("Authentication failed")

# What this code does: authenticates a local client and accepts only fresh,
# increasing message timestamps to demonstrate basic replay detection.
