"""Staging server must never fall back off port 8111.

Regression: a tester on Codex saw "port 8111 occupied" and the agent
improvised a second server on 8112 + announced a localhost URL. Occupied
8111 means the server is already running; the launcher must reuse it, exit
cleanly, and tell the agent NOT to pick another port.
"""

import os
import socket
import subprocess
import sys
import unittest
from pathlib import Path

REPO = Path(__file__).resolve().parents[1]
SERVER = REPO / "scripts" / "staging_server.py"


class BusyPortTest(unittest.TestCase):
    def test_exits_cleanly_and_says_reuse_when_port_busy(self):
        # Hold a port so staging_server.py sees EADDRINUSE.
        holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        holder.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        holder.bind(("127.0.0.1", 0))
        port = holder.getsockname()[1]
        holder.listen(1)
        try:
            out = subprocess.run(
                [sys.executable, str(SERVER), "--port", str(port)],
                capture_output=True, text=True, timeout=20,
            )
        finally:
            holder.close()

        # Must NOT crash with a traceback (which invited the 8112 improvisation).
        self.assertEqual(out.returncode, 0, out.stderr)
        self.assertNotIn("Traceback", out.stderr)
        msg = (out.stderr + out.stdout).lower()
        self.assertIn("already running", msg)
        self.assertIn("ensure_staging_server", msg)
        # Never suggests a different port.
        self.assertNotIn("8112", msg)


if __name__ == "__main__":
    unittest.main()
