import http.client
import socketserver
import threading
import sys
from pathlib import Path

sys.path.insert(0, ".")
from tools.serve_web_pc import FreeExilePCRequestHandler

s = socketserver.TCPServer(("127.0.0.1", 0), FreeExilePCRequestHandler)
port = s.server_address[1]
t = threading.Thread(target=s.serve_forever, daemon=True)
t.start()

vectors = [
    "/../../../../Windows/win.ini",
    "/../../.git/config",
    "/web_pc/../../../../Windows/win.ini",
    "/%2e%2e/%2e%2e/Windows/win.ini",
    "/C:/Windows/win.ini",
    "/..%2f..%2fWindows%2fwin.ini",
    "/%252e%252e/%252e%252e/Windows/win.ini",
    "/web_pc/..\\..\\Windows\\win.ini",
    "/....//....//Windows/win.ini",
    "/..",
    "/web_pc/..",
    "/../",
    "/web_pc/../webapp/index.html",
    "/web_pc/../.env",
    "//Windows/win.ini",
    "/..\\..\\..\\Windows\\win.ini"
]

results = []
for v in vectors:
    conn = http.client.HTTPConnection("127.0.0.1", port)
    conn.request("GET", v)
    res = conn.getresponse()
    body = res.read()
    results.append((v, res.status, len(body)))
    conn.close()

valid_checks = [
    "/",
    "/index.html",
    "/js/pc_main.js",
    "/css/pc_main.css"
]
valid_results = []
for v in valid_checks:
    conn = http.client.HTTPConnection("127.0.0.1", port)
    conn.request("GET", v)
    res = conn.getresponse()
    body = res.read()
    valid_results.append((v, res.status, len(body)))
    conn.close()

s.shutdown()

print("=== ADVERSARIAL TRAVERSAL RESULTS ===")
all_traversal_404 = True
for v, status, length in results:
    print(f"Path: {v:45} | Status: {status} | Length: {length}")
    if status != 404:
        all_traversal_404 = False

print("\n=== VALID ENDPOINT RESULTS ===")
all_valid_200 = True
for v, status, length in valid_results:
    print(f"Path: {v:45} | Status: {status} | Length: {length}")
    if status != 200:
        all_valid_200 = False

if all_traversal_404:
    print("\nTraversal Defense: PASS (100% returned 404)")
else:
    print("\nTraversal Defense: FAIL")

if all_valid_200:
    print("Valid Serving: PASS (100% returned 200)")
else:
    print("Valid Serving: FAIL")

assert all_traversal_404, "Security violation: some traversal paths did not return 404!"
assert all_valid_200, "Availability violation: some valid paths failed to serve!"
print("\nAUDIT CHECK 1 EMPIRICAL VERIFICATION: COMPLETE AND CLEAN")
