"""Tests for PeerDrop Daemon lifecycle module."""

import os
import tempfile
from pathlib import Path
from unittest.mock import MagicMock

from peerdrop.daemon.lifecycle import (
    Daemon,
    kill_daemon,
    read_pid_file,
    remove_pid_file,
    write_pid_file,
)


class TestPidFile:
    def test_write_and_read(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            pid_path = Path(tmpdir) / "test.pid"
            write_pid_file(pid_path)
            assert pid_path.exists()

            pid = read_pid_file(pid_path)
            assert pid == os.getpid()

    def test_read_nonexistent(self):
        pid = read_pid_file(Path("/nonexistent/path.pid"))
        assert pid is None

    def test_remove_pid_file(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            pid_path = Path(tmpdir) / "test.pid"
            write_pid_file(pid_path)
            assert pid_path.exists()

            remove_pid_file(pid_path)
            assert not pid_path.exists()

    def test_remove_nonexistent(self):
        # Should not raise
        remove_pid_file(Path("/nonexistent/path.pid"))


class TestDaemon:
    def test_is_running_no_pid_file(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            pid_path = Path(tmpdir) / "test.pid"
            daemon = Daemon.__new__(Daemon)
            daemon._pid_path = pid_path
            assert daemon.is_running() is False

    def test_is_running_stale_pid(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            pid_path = Path(tmpdir) / "test.pid"
            # Write a PID that doesn't exist
            pid_path.write_text("999999999")

            daemon = Daemon.__new__(Daemon)
            daemon._pid_path = pid_path
            assert daemon.is_running() is False
            # Stale PID file should be cleaned up
            assert not pid_path.exists()

    def test_get_status_not_started(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            pid_path = Path(tmpdir) / "test.pid"
            sock_path = Path(tmpdir) / "test.sock"

            daemon = Daemon.__new__(Daemon)
            daemon._pid_path = pid_path
            daemon._sock_path = sock_path
            daemon._engine = MagicMock()
            daemon._engine._started = False

            status = daemon.get_status()
            assert status["running"] is False
            assert status["peer_id"] is None


class TestKillDaemon:
    def test_kill_no_pid_file(self):
        result = kill_daemon(Path("/nonexistent/path.pid"))
        assert result is False

    def test_kill_stale_pid(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            pid_path = Path(tmpdir) / "test.pid"
            pid_path.write_text("999999999")

            result = kill_daemon(pid_path)
            assert result is False
            # Stale PID file should be cleaned up
            assert not pid_path.exists()
