"""
Shared Drive management for Google Drive integration.
"""

from __future__ import annotations

import logging
import uuid
from typing import TYPE_CHECKING

from googleapiclient.errors import HttpError

from slack_chat_migrator.core.config import MigrationConfig
from slack_chat_migrator.utils.logging import (
    log_with_context,
)

if TYPE_CHECKING:
    from slack_chat_migrator.services.drive_adapter import DriveAdapter


class SharedDriveManager:
    """Manages Google Drive shared drives for the migration process."""

    def __init__(
        self,
        drive_service: DriveAdapter,
        config: MigrationConfig,
    ) -> None:
        """Initialize the SharedDriveManager.

        Args:
            drive_service: Typed Drive API adapter
            config: Migration configuration
        """
        self.drive_service = drive_service
        self.config = config

    def validate_shared_drive(self, shared_drive_id: str) -> bool:
        """Validate that a shared drive exists and is accessible.

        Args:
            shared_drive_id: ID of the shared drive to validate

        Returns:
            True if valid and accessible, False otherwise
        """
        try:
            self.drive_service.get_drive(drive_id=shared_drive_id)
            return True
        except HttpError as e:
            log_with_context(
                logging.WARNING, f"Shared drive {shared_drive_id} not accessible: {e}"
            )
            return False

    def get_or_create_shared_drive(self) -> str | None:
        """Get or create the shared drive for storing attachments.

        Returns:
            Shared drive ID if successful, None otherwise
        """
        try:
            # Get shared drive configuration
            shared_drive_name = self.config.shared_drive.name
            shared_drive_id = self.config.shared_drive.id

            # If no shared drive specified, use default name
            if not shared_drive_name and not shared_drive_id:
                shared_drive_name = "Imported Slack Attachments"

            # Try to use specified shared drive ID
            if shared_drive_id:
                try:
                    drive_info = self.drive_service.get_drive(drive_id=shared_drive_id)
                    log_with_context(
                        logging.INFO,
                        f"Using configured shared drive: {drive_info.get('name', 'Unknown')} (ID: {shared_drive_id})",
                    )
                    drive_id_result: str | None = shared_drive_id
                    return drive_id_result
                except HttpError as e:
                    log_with_context(
                        logging.ERROR,
                        f"Configured shared drive ID {shared_drive_id} not accessible: {e}. Will create new one.",
                    )

            # Find existing shared drive by name or create new one
            if shared_drive_name:
                return self._find_or_create_shared_drive(shared_drive_name)

            return None

        except HttpError as e:
            log_with_context(
                logging.ERROR, f"Failed to get or create shared drive: {e}"
            )
            return None

    def _find_or_create_shared_drive(self, drive_name: str) -> str | None:
        """Find an existing shared drive by name or create a new one.

        Args:
            drive_name: Name of the shared drive to find or create

        Returns:
            Shared drive ID if successful, None otherwise
        """
        try:
            # First, search for existing shared drives with this name
            log_with_context(
                logging.INFO, f"Searching for existing shared drive: {drive_name}"
            )

            drives_list = self.drive_service.list_drives()
            drives = drives_list.get("drives", [])

            for drive in drives:
                if drive.get("name") == drive_name:
                    found_drive_id: str | None = drive.get("id")
                    log_with_context(
                        logging.INFO,
                        f"Found existing shared drive: {drive_name} (ID: {found_drive_id})",
                    )
                    return found_drive_id

            # Create new shared drive if not found
            log_with_context(logging.INFO, f"Creating new shared drive: {drive_name}")

            # Generate a unique request ID for idempotent creation
            request_id = str(uuid.uuid4())

            drive_metadata = {"name": drive_name}

            created_drive = self.drive_service.create_drive(
                body=drive_metadata, request_id=request_id
            )

            created_drive_id: str | None = created_drive.get("id")

            log_with_context(
                logging.INFO,
                f"Successfully created shared drive: {drive_name} (ID: {created_drive_id})",
            )

            return created_drive_id

        except HttpError as e:
            log_with_context(
                logging.ERROR,
                f"Failed to find or create shared drive {drive_name}: {e}",
            )
            return None
