"""Tests for reminders skill handler."""

import os
from unittest.mock import patch

import pytest

from fliiq.runtime.package_data import bundled_skills_dir
from fliiq.runtime.skills.base import SkillBase

SKILLS_DIR = str(bundled_skills_dir())


def _load_skill(name: str) -> SkillBase:
    return SkillBase(os.path.join(SKILLS_DIR, name))


def test_reminders_skill_loads():
    skill = _load_skill("reminders")
    assert skill.name == "reminders"
    schema = skill.schema()
    assert "action" in schema["parameters"]["properties"]
    assert "set" in schema["parameters"]["properties"]["action"]["enum"]


def _setup_fliiq(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    fliiq_dir = tmp_path / ".fliiq"
    fliiq_dir.mkdir()
    (fliiq_dir / "jobs").mkdir()
    return fliiq_dir


async def test_set_onetime_reminder_iso(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    # Mock ensure_daemon_running to avoid starting real daemon
    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        result = await handler({
            "action": "set",
            "message": "Call Sarah",
            "fire_at": "2026-03-01T09:00:00",
            "channel": "telegram",
        })

    assert result["success"] is True
    assert result["reminder_name"].startswith("reminder-")
    assert "2026-03-01" in result["schedule"]

    # Verify job YAML was created
    jobs_dir = tmp_path / ".fliiq" / "jobs"
    job_files = list(jobs_dir.glob("reminder-*.yaml"))
    assert len(job_files) == 1


async def test_set_onetime_reminder_natural_language(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        result = await handler({
            "action": "set",
            "message": "Review report",
            "fire_at": "tomorrow at 9am",
            "channel": "email",
        })

    assert result["success"] is True
    assert result["reminder_name"].startswith("reminder-")


async def test_set_recurring_reminder(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        result = await handler({
            "action": "set",
            "message": "Weekly standup",
            "recurring": "0 9 * * 1",
            "channel": "telegram",
        })

    assert result["success"] is True
    assert result["schedule"] == "0 9 * * 1"

    # Verify job YAML
    jobs_dir = tmp_path / ".fliiq" / "jobs"
    import yaml

    job_file = list(jobs_dir.glob("reminder-*.yaml"))[0]
    job_data = yaml.safe_load(job_file.read_text())
    assert job_data["trigger"]["type"] == "cron"
    assert job_data["trigger"]["schedule"] == "0 9 * * 1"


async def test_set_requires_message(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    with pytest.raises(ValueError, match="message is required"):
        await handler({"action": "set", "fire_at": "2026-03-01T09:00:00"})


async def test_set_requires_fire_at_or_recurring(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    with pytest.raises(ValueError, match="fire_at is required"):
        await handler({"action": "set", "message": "Test"})


async def test_list_reminders(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        await handler({"action": "set", "message": "Reminder 1", "fire_at": "2026-03-01T09:00:00"})
        await handler({"action": "set", "message": "Reminder 2", "fire_at": "2026-03-02T09:00:00"})

    result = await handler({"action": "list"})
    assert result["success"] is True
    assert result["count"] == 2
    assert all(r["name"].startswith("reminder-") for r in result["reminders"])


async def test_list_excludes_non_reminder_jobs(tmp_path, monkeypatch):
    fliiq_dir = _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    # Create a non-reminder job manually
    import yaml

    jobs_dir = fliiq_dir / "jobs"
    (jobs_dir / "my-regular-job.yaml").write_text(yaml.dump({
        "name": "my-regular-job",
        "trigger": {"type": "cron", "schedule": "0 * * * *"},
        "prompt": "Do something",
    }))

    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        await handler({"action": "set", "message": "My reminder", "fire_at": "2026-03-01T09:00:00"})

    result = await handler({"action": "list"})
    assert result["count"] == 1
    assert result["reminders"][0]["name"].startswith("reminder-")


async def test_cancel_reminder(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        r = await handler({"action": "set", "message": "Cancel me", "fire_at": "2026-03-01T09:00:00"})

    name = r["reminder_name"]
    result = await handler({"action": "cancel", "reminder_name": name})
    assert result["success"] is True

    # Verify it's gone
    result = await handler({"action": "list"})
    assert result["count"] == 0


async def test_cancel_requires_name(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    with pytest.raises(ValueError, match="reminder_name is required"):
        await handler({"action": "cancel"})


async def test_default_channel_is_telegram(tmp_path, monkeypatch):
    _setup_fliiq(tmp_path, monkeypatch)
    from fliiq.data.skills.core.reminders.main import handler

    with patch("fliiq.runtime.scheduler.daemon_utils.ensure_daemon_running", return_value=True):
        result = await handler({"action": "set", "message": "Test", "fire_at": "2026-03-01T09:00:00"})

    import yaml

    jobs_dir = tmp_path / ".fliiq" / "jobs"
    job_file = list(jobs_dir.glob("reminder-*.yaml"))[0]
    job_data = yaml.safe_load(job_file.read_text())
    assert "send_telegram" in job_data["skills"]
    assert "telegram" in job_data["prompt"]
