"""Malware scanning service."""

from typing import Any, Dict
from sed_sh.services.base import BaseService
import os


class MalwareService(BaseService):
    """Service for malware scanning.

    All methods may raise SedSHError or its subclasses on error.
    """

    def scan_file(self, file_path: str) -> Dict[str, Any]:
        """Scan a file for malware.

        This operation happens in two steps:
        1. Request an upload URL from the API
        2. Upload the file to S3 using the pre-signed URL

        Scan results are sent via email notification when complete (typically 1-2 minutes).

        Args:
            file_path: Path to the file to scan

        Returns:
            Dict containing:
                - scanId (str): Unique scan identifier
                - status (str): Initial status ("pending")
                - fileName (str): Name of the uploaded file
                - fileSize (int): Size of the file in bytes

        Raises:
            FileNotFoundError: If file doesn't exist
            InvalidRequestError: If file is too large (max 150 GB)
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> scan = client.malware.scan_file("/path/to/file.pdf")
            >>> print(f"Scan ID: {scan['scanId']}")
            >>> print("You'll receive an email when the scan completes")
        """
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"File not found: {file_path}")

        file_name = os.path.basename(file_path)
        file_size = os.path.getsize(file_path)

        # Determine content type
        content_type = "application/octet-stream"
        if file_name.endswith(".pdf"):
            content_type = "application/pdf"
        elif file_name.endswith((".jpg", ".jpeg")):
            content_type = "image/jpeg"
        elif file_name.endswith(".png"):
            content_type = "image/png"
        elif file_name.endswith(".zip"):
            content_type = "application/zip"

        # Step 1: Request upload URL
        upload_response = self._request(
            "POST",
            "/malware/upload",
            json={
                "fileName": file_name,
                "fileSize": file_size,
                "contentType": content_type,
            },
        )

        upload_url = upload_response.get("uploadUrl")
        scan_id = upload_response.get("scanId")

        # Step 2: Upload file to S3
        with open(file_path, "rb") as f:
            file_data = f.read()

        import requests

        upload_result = requests.put(
            upload_url,
            data=file_data,
            headers={"Content-Type": content_type},
            timeout=self.timeout,
        )
        upload_result.raise_for_status()

        # Return scan information
        return {
            "scanId": scan_id,
            "status": "pending",
            "fileName": file_name,
            "fileSize": file_size,
        }
