"""Integration manager: registers and manages external service integrations."""

from __future__ import annotations

import logging

from agntspace.integrations.base import Integration, IntegrationStatus

log = logging.getLogger(__name__)


class IntegrationManager:
    """Manages all external service integrations."""

    def __init__(self) -> None:
        self._integrations: dict[str, Integration] = {}

    def register(self, integration: Integration) -> None:
        self._integrations[integration.name] = integration

    def get(self, name: str) -> Integration | None:
        return self._integrations.get(name)

    async def connect(self, name: str, credentials: dict) -> IntegrationStatus:
        """Connect a specific integration."""
        integration = self._integrations.get(name)
        if not integration:
            return IntegrationStatus(name=name, connected=False, error="Unknown integration")
        await integration.connect(credentials)
        return await integration.check_status()

    async def disconnect(self, name: str) -> None:
        integration = self._integrations.get(name)
        if integration:
            await integration.disconnect()

    async def list_integrations(self) -> list[dict]:
        """List all integrations with status."""
        results = []
        for integration in self._integrations.values():
            status = await integration.check_status()
            results.append({
                "name": status.name,
                "description": integration.description,
                "connected": status.connected,
                "last_sync": status.last_sync,
            })
        return results

    async def sync_all(self) -> dict:
        """Sync all connected integrations."""
        results = {}
        for name, integration in self._integrations.items():
            if integration.is_connected:
                results[name] = await integration.sync()
        return results
