"""Tests for create_job / delete_job / list_jobs tool registration and execution."""

import asyncio
from pathlib import Path
from unittest.mock import patch

from fliiq.runtime.agent.tools import ToolRegistry
from fliiq.runtime.scheduler.loader import load_job, 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_tool_registered(tmp_path):
    """Job tools appear when project_root is provided in non-plan mode."""
    reg = ToolRegistry()
    reg.register_builtins(mode="autonomous", project_root=tmp_path)
    names = {d["name"] for d in reg.get_tool_definitions()}
    assert "create_job" in names
    assert "delete_job" in names
    assert "list_jobs" in names


def test_create_job_tool_not_in_plan_mode(tmp_path):
    """Job tools absent in plan mode (plan mode has mode != 'plan' check)."""
    reg = ToolRegistry()
    reg.register_builtins(mode="plan", project_root=tmp_path)
    names = {d["name"] for d in reg.get_tool_definitions()}
    assert "create_job" not in names


def test_job_tools_not_registered_without_project_root():
    """Job tools absent when project_root is None."""
    reg = ToolRegistry()
    reg.register_builtins(mode="autonomous")
    names = {d["name"] for d in reg.get_tool_definitions()}
    assert "create_job" not in names
    assert "delete_job" not in names
    assert "list_jobs" not in names


def test_create_job_tool_execute(tmp_path):
    jobs_dir = _setup(tmp_path)
    reg = ToolRegistry()

    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        reg.register_builtins(mode="autonomous", project_root=tmp_path)

        result = asyncio.run(reg.execute("create_job", {
            "name": "tool-job",
            "prompt": "Do something",
            "trigger_type": "every",
            "schedule": "30s",
        }))

    assert "created" in result.lower()
    assert (jobs_dir / "tool-job.yaml").exists()
    job = load_job(jobs_dir / "tool-job.yaml")
    assert job.name == "tool-job"


def test_list_jobs_tool_execute(tmp_path):
    jobs_dir = _setup(tmp_path)
    save_job(_make_job("listed-job"), jobs_dir)

    reg = ToolRegistry()
    reg.register_builtins(mode="autonomous", project_root=tmp_path)

    result = asyncio.run(reg.execute("list_jobs", {}))
    assert "listed-job" in result


def test_delete_job_tool_execute(tmp_path):
    jobs_dir = _setup(tmp_path)
    save_job(_make_job("doomed"), jobs_dir)
    assert (jobs_dir / "doomed.yaml").exists()

    reg = ToolRegistry()
    reg.register_builtins(mode="autonomous", project_root=tmp_path)

    result = asyncio.run(reg.execute("delete_job", {"name": "doomed"}))
    assert "deleted" in result.lower()
    assert not (jobs_dir / "doomed.yaml").exists()
