"""System workspace health validator for the 43-node prime array.

Confirms tcp/8000 (server) and tcp/8081 (engine) are both reachable and that
a 348-byte frame from engine starts with the 0x434E4D54 marker.
"""

import socket
import struct
import sys


def verify_port(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1.0)
    try:
        s.connect((host, port))
        print(f" -> Port {port:4d}: [ONLINE] connection mapped")
        return True
    except socket.error:
        print(f" -> Port {port:4d}: [OFFLINE] pipeline closed or blocked")
        return False
    finally:
        s.close()


def validate():
    print("==========================================================")
    print("      EXECUTING SYSTEM WORKSPACE HEALTH VALIDATION        ")
    print("==========================================================")

    print("Direction: testing active connection ports...")
    ui_ok = verify_port("127.0.0.1", 8000)
    engine_ok = verify_port("127.0.0.1", 8081)
    if not (ui_ok and engine_ok):
        print("\n[VALIDATION FAILED]: launch engine.py and server.py first")
        sys.exit(1)

    print("\nDirection: verifying data pipeline packet integrity...")
    try:
        pipe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        pipe.connect(("127.0.0.1", 8081))
        buf = pipe.recv(348)
        pipe.close()
    except Exception as e:
        print(f" -> Data integrity step fault: {e}")
        sys.exit(1)

    if len(buf) != 348:
        print(f" -> Packet Size Check: [FAILED] got {len(buf)} bytes (expected 348)")
        sys.exit(1)
    print(" -> Packet Size Check: [PASSED] exactly 348 bytes captured")

    marker = struct.unpack("!I", buf[0:4])[0]
    if marker == 0x434E4D54:
        print(" -> Identity Marker   : [PASSED] 0x434E4D54 (\"43MT\")")
    else:
        print(f" -> Identity Marker   : [FAILED] got 0x{marker:08X}")

    print("\n==========================================================")
    print(" STATUS: ALL NETWORK AND DATA PIPELINES OPERATING OPTIMAL ")
    print("==========================================================")


if __name__ == "__main__":
    validate()
