import pytest
import tempfile
import uuid
from api.crontab_manager import CrontabManager


@pytest.fixture
def crontab_file():
    with tempfile.NamedTemporaryFile(mode="w+", delete=False) as f:
        pass
    yield f.name


def test_crontab_manager_empty(crontab_file):
    manager = CrontabManager(tabfile=crontab_file)
    assert manager.get_alarms() == []


def test_add_and_list_alarm(crontab_file):
    manager = CrontabManager(tabfile=crontab_file)
    alarm_id = str(uuid.uuid4())
    manager.set_alarm(
        alarm_id=alarm_id,
        cron_expression="30 7 * * *",
        command="python wecker.py",
        is_enabled=True,
    )

    alarms = manager.get_alarms()
    assert len(alarms) == 1
    assert alarms[0]["id"] == alarm_id
    assert alarms[0]["cron_expression"] == "30 7 * * *"
    assert alarms[0]["command"] == "python wecker.py"
    assert alarms[0]["is_enabled"] is True


def test_update_alarm(crontab_file):
    manager = CrontabManager(tabfile=crontab_file)
    alarm_id = "test-id"
    manager.set_alarm(
        alarm_id=alarm_id,
        cron_expression="30 7 * * *",
        command="python wecker.py",
        is_enabled=True,
    )

    manager.set_alarm(
        alarm_id=alarm_id,
        cron_expression="0 8 * * *",
        command="python wecker.py --loud",
        is_enabled=False,
    )

    alarms = manager.get_alarms()
    assert len(alarms) == 1
    assert alarms[0]["cron_expression"] == "0 8 * * *"
    assert alarms[0]["command"] == "python wecker.py --loud"
    assert alarms[0]["is_enabled"] is False


def test_delete_alarm(crontab_file):
    manager = CrontabManager(tabfile=crontab_file)
    alarm_id = "test-id-2"
    manager.set_alarm(alarm_id, "0 0 * * *", "cmd", True)
    assert len(manager.get_alarms()) == 1

    manager.delete_alarm(alarm_id)
    assert len(manager.get_alarms()) == 0
