"""
Tests for task deletion and download restoration features
"""
import pytest
import os
from pathlib import Path
from datetime import datetime
from unittest.mock import patch, MagicMock

from app.models import DownloadTask, DownloadStatus, HostType
from app.download_manager import DownloadManager


class TestDeleteTask:
    """Tests for delete_task method"""

    @pytest.mark.asyncio
    async def test_delete_task_removes_from_dict(self, download_manager):
        """Test that delete_task removes task from tasks dict"""
        # Create a task
        from app.models import DownloadRequest
        request = DownloadRequest(url="https://example.com/file.mp4")
        task = download_manager.create_task(request)

        # Verify task exists
        assert task.id in download_manager.tasks
        assert len(download_manager.tasks) == 1

        # Delete the task
        await download_manager.delete_task(task.id)

        # Verify task is removed
        assert task.id not in download_manager.tasks
        assert len(download_manager.tasks) == 0

    @pytest.mark.asyncio
    async def test_delete_task_completed_keeps_file(self, download_manager, temp_download_dir):
        """Test that delete_task keeps files for completed downloads"""
        from app.models import DownloadRequest
        request = DownloadRequest(url="https://example.com/file.mp4")
        task = download_manager.create_task(request)
        task.status = DownloadStatus.COMPLETED

        # Create a dummy file
        test_file = temp_download_dir / "test_completed.mp4"
        test_file.write_text("completed content")
        task.file_path = str(test_file)

        # Delete the task (file should be kept)
        await download_manager.delete_task(task.id)

        # Verify task is removed
        assert task.id not in download_manager.tasks
        # File should still exist
        assert test_file.exists()

    @pytest.mark.asyncio
    async def test_delete_task_pending_deletes_file(self, download_manager, temp_download_dir):
        """Test that delete_task deletes files for pending downloads"""
        from app.models import DownloadRequest
        request = DownloadRequest(url="https://example.com/file.mp4")
        task = download_manager.create_task(request)
        task.status = DownloadStatus.PENDING

        # Create a dummy file
        test_file = temp_download_dir / "test_pending.mp4"
        test_file.write_text("pending content")
        task.file_path = str(test_file)

        # Delete the task (file should be deleted)
        await download_manager.delete_task(task.id)

        # Verify task is removed
        assert task.id not in download_manager.tasks
        # File should be deleted
        assert not test_file.exists()

    @pytest.mark.asyncio
    async def test_delete_task_downloading_deletes_file(self, download_manager, temp_download_dir):
        """Test that delete_task deletes files for downloading tasks"""
        from app.models import DownloadRequest
        request = DownloadRequest(url="https://example.com/file.mp4")
        task = download_manager.create_task(request)
        task.status = DownloadStatus.DOWNLOADING

        # Create a dummy file
        test_file = temp_download_dir / "test_downloading.mp4"
        test_file.write_text("downloading content")
        task.file_path = str(test_file)

        # Delete the task (file should be deleted)
        await download_manager.delete_task(task.id)

        # Verify task is removed
        assert task.id not in download_manager.tasks
        # File should be deleted
        assert not test_file.exists()

    @pytest.mark.asyncio
    async def test_delete_task_nonexistent(self, download_manager):
        """Test that delete_task handles nonexistent task gracefully"""
        # Should not raise an error
        await download_manager.delete_task("nonexistent-id")

    @pytest.mark.asyncio
    async def test_delete_task_with_active_download(self, download_manager):
        """Test that delete_task cancels active downloads"""
        from app.models import DownloadRequest
        request = DownloadRequest(url="https://example.com/file.mp4")
        task = download_manager.create_task(request)

        # Mock an active download
        mock_task = MagicMock()
        mock_task.cancel = MagicMock()
        download_manager.active_downloads[task.id] = mock_task

        # Delete the task
        await download_manager.delete_task(task.id)

        # Verify active download was cancelled
        mock_task.cancel.assert_called_once()
        assert task.id not in download_manager.active_downloads

    @pytest.mark.asyncio
    async def test_delete_task_cancelled_status(self, download_manager):
        """Test delete_task with cancelled status removes task"""
        from app.models import DownloadRequest
        request = DownloadRequest(url="https://example.com/file.mp4")
        task = download_manager.create_task(request)
        task.status = DownloadStatus.CANCELLED

        # Delete the task
        await download_manager.delete_task(task.id)

        # Verify task is removed
        assert task.id not in download_manager.tasks

    @pytest.mark.asyncio
    async def test_delete_task_failed_status(self, download_manager):
        """Test delete_task with failed status removes task"""
        from app.models import DownloadRequest
        request = DownloadRequest(url="https://example.com/file.mp4")
        task = download_manager.create_task(request)
        task.status = DownloadStatus.FAILED

        # Delete the task
        await download_manager.delete_task(task.id)

        # Verify task is removed
        assert task.id not in download_manager.tasks

