import json
import pytest
from taskr import storage


@pytest.fixture(autouse=True)
def isolated_storage(tmp_path, monkeypatch):
    """Redirect DB_FILE and _LEGACY_JSON to temp paths so tests don't touch ~/.taskr/."""
    monkeypatch.setattr(storage, "DB_FILE", tmp_path / "tasks.db")
    monkeypatch.setattr(storage, "_LEGACY_JSON", tmp_path / "tasks.json")


def test_add_task():
    task = storage.add_task("Buy milk")
    assert task["id"] == 1
    assert task["text"] == "Buy milk"
    assert task["done"] is False


def test_add_multiple_tasks_increments_id():
    storage.add_task("Task one")
    task = storage.add_task("Task two")
    assert task["id"] == 2


def test_get_tasks_empty():
    assert storage.get_tasks() == []


def test_get_tasks_returns_all():
    storage.add_task("Task one")
    storage.add_task("Task two")
    assert len(storage.get_tasks()) == 2


def test_mark_done():
    storage.add_task("Do laundry")
    task = storage.mark_done(1)
    assert task["done"] is True
    assert storage.get_tasks()[0]["done"] is True


def test_mark_done_persists():
    storage.add_task("Persist this")
    storage.mark_done(1)
    tasks = storage.get_tasks()
    assert tasks[0]["done"] is True


def test_mark_done_nonexistent():
    assert storage.mark_done(99) is None


def test_delete_task():
    storage.add_task("To delete")
    task = storage.delete_task(1)
    assert task["text"] == "To delete"
    assert storage.get_tasks() == []


def test_delete_nonexistent():
    assert storage.delete_task(99) is None


def test_delete_does_not_affect_others():
    storage.add_task("Keep this")
    storage.add_task("Delete this")
    storage.delete_task(2)
    tasks = storage.get_tasks()
    assert len(tasks) == 1
    assert tasks[0]["text"] == "Keep this"


def test_migrate_from_json(tmp_path, monkeypatch):
    """tasks.json should be imported into SQLite and renamed to .bak."""
    legacy = tmp_path / "tasks.json"
    legacy.write_text(json.dumps([
        {"id": 1, "text": "Imported task", "done": False},
        {"id": 2, "text": "Done task",     "done": True},
    ]))
    monkeypatch.setattr(storage, "_LEGACY_JSON", legacy)

    tasks = storage.get_tasks()

    assert len(tasks) == 2
    assert tasks[0]["text"] == "Imported task"
    assert tasks[0]["done"] is False
    assert tasks[1]["done"] is True
    assert not legacy.exists()
    assert (tmp_path / "tasks.json.bak").exists()


def test_migrate_skipped_when_db_exists(tmp_path):
    """If tasks.db already exists, tasks.json should not be touched."""
    # Seed the DB first — this creates tasks.db
    storage.add_task("Pre-existing task")

    # Now create the legacy file; migration should not run since DB exists
    legacy = tmp_path / "tasks.json"  # same path as autouse fixture
    legacy.write_text(json.dumps([{"id": 99, "text": "Should not import", "done": False}]))

    tasks = storage.get_tasks()
    assert len(tasks) == 1
    assert tasks[0]["text"] == "Pre-existing task"
    assert legacy.exists()  # untouched
