"""Tests for job CRUD layer (tool-facing)."""

from unittest.mock import patch

from fliiq.runtime.scheduler.job_crud import (
    create_job_from_params,
    delete_job_by_name,
    list_jobs_summary,
)
from fliiq.runtime.scheduler.loader import save_job
from fliiq.runtime.scheduler.models import JobDefinition, TriggerConfig


def _make_job(name: str = "test-job") -> JobDefinition:
    return JobDefinition(
        name=name,
        trigger=TriggerConfig(type="cron", schedule="0 9 * * *"),
        prompt="Test prompt",
    )


def _setup(tmp_path):
    jobs_dir = tmp_path / ".fliiq" / "jobs"
    jobs_dir.mkdir(parents=True)
    return jobs_dir


def test_create_job_from_params(tmp_path):
    _setup(tmp_path)
    params = {
        "name": "my-job",
        "prompt": "Do stuff",
        "trigger_type": "cron",
        "schedule": "0 9 * * *",
    }
    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        result = create_job_from_params(params, tmp_path)

    assert "created" in result.lower()
    assert "Daemon started" in result
    assert (tmp_path / ".fliiq" / "jobs" / "my-job.yaml").exists()


def test_create_job_invalid_name(tmp_path):
    _setup(tmp_path)
    params = {
        "name": "INVALID NAME",
        "prompt": "Do stuff",
        "trigger_type": "cron",
        "schedule": "0 9 * * *",
    }
    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        result = create_job_from_params(params, tmp_path)

    assert "error" in result.lower()


def test_create_job_duplicate(tmp_path):
    jobs_dir = _setup(tmp_path)
    save_job(_make_job("dup-job"), jobs_dir)

    params = {
        "name": "dup-job",
        "prompt": "Another prompt",
        "trigger_type": "cron",
        "schedule": "0 9 * * *",
    }
    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        result = create_job_from_params(params, tmp_path)

    assert "already exists" in result.lower()


def test_delete_job_by_name(tmp_path):
    jobs_dir = _setup(tmp_path)
    save_job(_make_job("del-me"), jobs_dir)
    assert (jobs_dir / "del-me.yaml").exists()

    result = delete_job_by_name("del-me", tmp_path)
    assert "deleted" in result.lower()
    assert not (jobs_dir / "del-me.yaml").exists()


def test_delete_job_not_found(tmp_path):
    _setup(tmp_path)
    result = delete_job_by_name("ghost", tmp_path)
    assert "not found" in result.lower()


def test_list_jobs_summary_empty(tmp_path):
    _setup(tmp_path)
    result = list_jobs_summary(tmp_path)
    assert "No jobs" in result


def test_list_jobs_summary(tmp_path):
    jobs_dir = _setup(tmp_path)
    save_job(_make_job("alpha"), jobs_dir)
    save_job(_make_job("bravo"), jobs_dir)

    result = list_jobs_summary(tmp_path)
    assert "alpha" in result
    assert "bravo" in result
