import contextlib
import http.client
import os
import signal
import socket
import subprocess
import sys
import tempfile
import time

import pytest


@contextlib.contextmanager
def managed(*options, app='tests.s_supervised:app', module_dir=None):
  sock = socket.socket()
  sock.bind(('127.0.0.1', 0))
  sock.listen()
  port = sock.getsockname()[1]
  with tempfile.TemporaryFile() as logs:
    env = dict(os.environ)
    if module_dir:
      env['PYTHONPATH'] = str(module_dir) + os.pathsep + env.get('PYTHONPATH', '')
    process = subprocess.Popen([
      sys.executable, '-m', 'mrhttp', app, '--fd', str(sock.fileno()), '--lifespan', 'off',
      '--timeout-graceful-shutdown', '1', '--timeout-worker-startup', '5',
      '--timeout-worker-healthcheck', '1', *options], pass_fds=(sock.fileno(),),
      stdout=logs, stderr=logs, start_new_session=True, env=env)
    try:
      deadline = time.monotonic() + 10
      while True:
        if process.poll() is not None:
          logs.seek(0)
          raise AssertionError(logs.read().decode(errors='replace'))
        try:
          request(port)
          break
        except (OSError, http.client.HTTPException):
          if time.monotonic() > deadline:
            raise AssertionError('Supervisor did not become ready')
          time.sleep(0.025)
      yield process, port
    finally:
      sock.close()
      if process.poll() is None:
        process.send_signal(signal.SIGTERM)
        try:
          process.wait(timeout=5)
        except subprocess.TimeoutExpired:
          os.killpg(process.pid, signal.SIGKILL)
          process.wait()
      if process.returncode:
        logs.seek(0)
        print(logs.read().decode(errors='replace'))


def request(port, path='/pid', timeout=0.3):
  client = http.client.HTTPConnection('127.0.0.1', port, timeout=timeout)
  try:
    client.request('GET', path)
    result = client.getresponse()
    assert result.status == 200
    return result.read()
  finally:
    client.close()


def wait_for_new_pid(port, old, timeout=6):
  deadline = time.monotonic() + timeout
  while time.monotonic() < deadline:
    try:
      value = request(port)
      if value != old:
        return value
    except (OSError, http.client.HTTPException):
      pass
    time.sleep(0.025)
  raise AssertionError('Worker was not replaced')


@pytest.mark.parametrize('failure', ['/crash', '/hang'])
def test_worker_failure_is_recovered_without_stopping_supervisor(failure):
  with managed('--workers', '1') as (process, port):
    old = request(port)
    with pytest.raises((OSError, http.client.HTTPException)):
      request(port, failure, timeout=2)
    assert wait_for_new_pid(port, old)
    assert process.poll() is None


def test_request_limit_recycles_worker():
  with managed('--limit-max-requests', '3', '--limit-max-requests-jitter', '1') as (process, port):
    old = request(port)
    assert wait_for_new_pid(port, old)
    assert process.poll() is None


def test_rolling_restart_loads_fresh_code_and_finishes_inflight_request(tmp_path):
  module = tmp_path / 'rolling_app.py'
  template = '''import asyncio
async def app(scope, receive, send):
    if scope['path'] == '/slow':
        await asyncio.sleep(0.8)
    await send({{'type': 'http.response.start', 'status': 200}})
    await send({{'type': 'http.response.body', 'body': {version!r}}})
'''
  module.write_text(template.format(version=b'old'))
  with managed(app='rolling_app:app', module_dir=tmp_path) as (process, port):
    old_client = http.client.HTTPConnection('127.0.0.1', port, timeout=3)
    try:
      old_client.request('GET', '/slow')
      time.sleep(0.05)
      module.write_text(template.format(version=b'new-version'))
      process.send_signal(signal.SIGHUP)
      deadline = time.monotonic() + 6
      while request(port) != b'new-version':
        assert time.monotonic() < deadline
        time.sleep(0.025)
      assert old_client.getresponse().read() == b'old'
      assert process.poll() is None
    finally:
      old_client.close()


def test_factory_and_shared_metrics_across_two_workers():
  with managed('--workers', '2', '--factory', '--metrics-path', '/metrics', app='tests.s_supervised:factory') as (_, port):
    seen = set()
    deadline = time.monotonic() + 5
    count = 0
    while time.monotonic() < deadline:
      body = request(port)
      count += 1
      assert body.startswith(b'factory:')
      seen.add(body)
      if len(seen) == 2:
        break
      time.sleep(0.01)
    assert len(seen) == 2
    metrics = request(port, '/metrics')
    assert b'mrhttp_http_requests_total{status="200"}' in metrics
    count_line = next(line for line in metrics.splitlines() if line.startswith(b'mrhttp_request_duration_seconds_count '))
    assert int(count_line.split()[-1]) >= count + 1
