from __future__ import annotations

import json
import os
from pathlib import Path
import signal
import sys

from scripts import serve_structure_review as service


def test_atomic_status_file_and_process_identity(tmp_path):
    path = tmp_path/'status.json'
    service.write_json(path, {'state': 'running', '中文': '状态'})
    assert service.read_json(path) == {'state': 'running', '中文': '状态'}
    assert not list(tmp_path.glob('*.tmp'))
    assert service.process_identity(os.getpid())
    assert service.process_identity(-1) is None


def test_tunnel_status_handles_partial_log_lines_and_disconnects(tmp_path):
    child = service.Child('tunnel', [], tmp_path, os.environ.copy())
    child.process = object()  # This test parses logs without launching Cloudflare.
    child.log_path = tmp_path/'tunnel.log'
    child.log_path.write_text('Your tunnel: https://safe-test.trycloudflare.com\nRegistered tunnel connec')
    assert child.read_tunnel_status()
    assert child.url == 'https://safe-test.trycloudflare.com' and not child.connected
    with child.log_path.open('a') as log: log.write('tion connIndex=0\n')
    assert child.read_tunnel_status() and child.connected
    assert not child.read_tunnel_status()
    with child.log_path.open('a') as log: log.write('Unregistered tunnel connection\n')
    assert child.read_tunnel_status() and not child.connected


def test_exited_child_restarts_without_touching_other_processes(tmp_path):
    child = service.Child('test', [sys.executable, '-c', 'raise SystemExit(7)'], tmp_path, os.environ.copy())
    assert child.ensure()
    first_log = child.log_path
    child.process.wait(timeout=10)
    assert child.ensure() and child.process is None
    assert not child.ensure()  # Backoff protects against rapid failure loops.
    child.retry_at = 0
    assert child.ensure() and child.starts == 2 and child.log_path != first_log
    child.process.wait(timeout=10)
    child.stop()
    assert first_log.exists() and child.log_path.exists()


def test_running_check_rejects_stale_pid_identity(tmp_path, monkeypatch):
    monkeypatch.setattr(service, 'STATE', tmp_path)
    status = {'pid': os.getpid(), 'process_identity': 'wrong-old-process'}
    service.write_json(tmp_path/'supervisor.json', status)
    assert service.running() is None
    status['process_identity'] = service.process_identity(os.getpid())
    service.write_json(tmp_path/'supervisor.json', status)
    assert service.running() == status
