"""Prueba HTTP real: arranque aislado, rutas y protección de archivos internos."""
import http.client
import json
from pathlib import Path
import shutil
import socket
import subprocess
import time

root = Path(__file__).resolve().parents[2]
with socket.socket() as sock:
    sock.bind(('127.0.0.1', 0))
    port = sock.getsockname()[1]

with subprocess.Popen(
    [shutil.which('php') or 'php', '-S', f'127.0.0.1:{port}',
     '-t', str(root / 'backend/public'), str(root / 'backend/public/index.php')],
    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
) as server:
    try:
        for _ in range(100):
            if server.poll() is not None:
                raise RuntimeError('PHP terminó antes de arrancar')
            try:
                with socket.create_connection(('127.0.0.1', port), timeout=0.1):
                    break
            except OSError:
                time.sleep(0.05)
        else:
            raise RuntimeError('PHP no arrancó en el tiempo esperado')

        cases = [('GET', '/api/v1/health', 200),
                 ('GET', '/api/v1/health?probe=1', 200),
                 ('HEAD', '/api/v1/health', 200),
                 ('POST', '/api/v1/health', 405),
                 ('GET', '/api/v1/missing', 404),
                 ('GET', '/.env', 404),
                 ('GET', '/backend/src/http.php', 404),
                 ('GET', '/docs/HomeCore_CODEX_START.md', 404)]
        for method, path, expected in cases:
            connection = http.client.HTTPConnection('127.0.0.1', port, timeout=3)
            try:
                connection.request(method, path)
                response = connection.getresponse()
                body = response.read()
                assert response.status == expected, (method, path, response.status)
                assert response.getheader('Content-Type') == 'application/json; charset=utf-8'
                assert response.getheader('Cache-Control') == 'no-store'
                if method == 'HEAD':
                    assert body == b''
                else:
                    data = json.loads(body)
                    if expected == 200:
                        assert data['status'] == 'ok'
                        assert data['service'] == 'homecore-api'
                        assert data['timestamp'].endswith('Z')
                    else:
                        assert 'code' in data['error']
                if expected == 405:
                    assert response.getheader('Allow') == 'GET, HEAD'
                print(f'PASS {method} {path} → {expected}')
            finally:
                connection.close()
    finally:
        server.terminate()
        server.wait(timeout=5)
