"""Tests for daemon-related functionality."""

import os
import signal
from unittest.mock import patch

from syke.daemon.daemon import (
    SykeDaemon,
    _write_pid,
    _remove_pid,
    is_running,
    generate_plist,
    PIDFILE,
)


def test_daemon_pid_lifecycle(tmp_path):
    """PID file is written and cleaned up correctly."""
    test_pidfile = tmp_path / "daemon.pid"
    with patch("syke.daemon.daemon.PIDFILE", test_pidfile):
        # Initially not running
        running, pid = is_running()
        assert running is False
        assert pid is None

        # Write PID
        _write_pid()
        assert test_pidfile.exists()
        written_pid = int(test_pidfile.read_text().strip())
        assert written_pid == os.getpid()

        # Should detect as running (our own PID)
        running, pid = is_running()
        assert running is True
        assert pid == os.getpid()

        # Remove PID
        _remove_pid()
        assert not test_pidfile.exists()

        # No longer running
        running, pid = is_running()
        assert running is False


def test_daemon_stale_pid_cleanup(tmp_path):
    """Stale PID file (dead process) is cleaned up automatically."""
    test_pidfile = tmp_path / "daemon.pid"
    # Write a PID that definitely doesn't exist (99999999)
    test_pidfile.write_text("99999999")

    with patch("syke.daemon.daemon.PIDFILE", test_pidfile):
        running, pid = is_running()
        assert running is False
        assert pid is None
        # PID file should be cleaned up
        assert not test_pidfile.exists()


def test_daemon_signal_stops_loop():
    """Daemon loop stops when signal handler sets running=False."""
    d = SykeDaemon("test", interval=1)
    assert d.running is True
    d._handle_signal(signal.SIGTERM, None)
    assert d.running is False


def test_generate_plist_source_install():
    """Source install plist uses sys.executable -m syke with WorkingDirectory."""
    import sys

    plist = generate_plist("testuser", source_install=True)
    assert "com.syke.daemon" in plist
    assert "testuser" in plist
    assert "<string>sync</string>" in plist
    assert "<?xml" in plist
    assert "StartInterval" in plist
    assert f"<string>{sys.executable}</string>" in plist
    assert "<string>-m</string>" in plist
    assert "WorkingDirectory" in plist


def test_generate_plist_pip_install():
    """Pip install plist uses syke console script, no -m, no WorkingDirectory."""
    plist = generate_plist("testuser", source_install=False)
    assert "com.syke.daemon" in plist
    assert "testuser" in plist
    assert "<string>sync</string>" in plist
    assert "<string>-m</string>" not in plist
    assert "WorkingDirectory" not in plist
    # Should reference the syke binary
    assert "syke" in plist


def test_generate_plist_with_api_key(monkeypatch):
    """API key is injected into plist EnvironmentVariables when set."""
    monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-test-key-123")
    plist = generate_plist("testuser", source_install=False)
    assert "ANTHROPIC_API_KEY" in plist
    assert "sk-ant-test-key-123" in plist
    assert "EnvironmentVariables" in plist


def test_generate_plist_no_api_key(monkeypatch):
    """No API key block when ANTHROPIC_API_KEY is unset."""
    monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
    plist = generate_plist("testuser", source_install=False)
    assert "ANTHROPIC_API_KEY" not in plist
    assert "EnvironmentVariables" not in plist
