import subprocess
import time
import requests
import os
import sys

TARGET_URL = "http://server:8080"
TARGET_HOST = "server"

TESTS = [
    {"name": "Garbage Flood", "cmd": ["python3", "/app/fuzzing/garbage_flood.py"]},
    {
        "name": "Malformed Handshake",
        "cmd": ["python3", "/app/protocol/malformed_handshake.py"],
    },
    {
        "name": "Slowloris (Stress)",
        "cmd": ["python3", "/app/stress/slowloris.py"],
        "duration": 10,
        "conns": "40",
    },
]


def check_health():
    for _ in range(3):
        try:
            r = requests.get(TARGET_URL, timeout=3)
            if r.status_code == 200:
                return True
        except:  # noqa: E722
            pass
        time.sleep(1)
    return False


def main():
    print("\n" + "=" * 40)
    print("      REFRACTIUM PENTEST SUITE")
    print("=" * 40)

    print("[*] Waiting for server...", end="", flush=True)
    ready = False
    for _ in range(30):
        if check_health():
            ready = True
            break
        print(".", end="", flush=True)
        time.sleep(1)

    if not ready:
        print("\n[!] ERROR: Server timed out")
        sys.exit(1)

    print(" READY")

    results = []
    for test in TESTS:
        print(f"[*] {test['name']:<25}...", end="", flush=True)

        env = os.environ.copy()
        env["TARGET"] = TARGET_HOST
        if "conns" in test:
            env["CONNECTIONS"] = test["conns"]

        proc = subprocess.Popen(
            test["cmd"], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
        time.sleep(test.get("duration", 2))

        success = check_health()
        results.append((test["name"], success))

        proc.terminate()
        proc.wait()
        print(" DONE")

    print("\n" + "#" * 40)
    print("##" + " " * 12 + "FINAL REPORT" + " " * 12 + "##")
    print("#" * 40)
    all_pass = True
    for name, success in results:
        status = "OK" if success else "FAIL"
        print(f"## {name:<25}: [{status}] ##")
        if not success:
            all_pass = False
    print("#" * 40)

    sys.exit(0 if all_pass else 1)


if __name__ == "__main__":
    main()
