"""OAuth credential service for rclone-backed filesystem mounts.

This service owns the encrypted rclone OAuth config fragment used by
relay-native rclone mounts. Filesystem services reference it through
`credential_service_id` instead of storing OAuth login actions directly.
"""

from __future__ import annotations

from typing import Any, Dict

from core import ServiceFactory, ServiceError
from core.base_service import BaseService


SERVICE_TYPE = "rcloneOAuthCredentials"
PROVIDERS = ("drive", "onedrive")


def normalize_provider(provider: str) -> str:
    key = (provider or "").strip().lower()
    aliases = {
        "google_drive": "drive",
        "google-drive": "drive",
        "gdrive": "drive",
        "one_drive": "onedrive",
        "one-drive": "onedrive",
    }
    return aliases.get(key, key)


def is_credential_service_def(sdef: Any, provider: str = "") -> bool:
    if not sdef or getattr(sdef, "service_type", "") != SERVICE_TYPE:
        return False
    if not provider:
        return True
    cfg = getattr(sdef, "config", {}) or {}
    return normalize_provider(cfg.get("provider", "")) == normalize_provider(provider)


class RcloneOAuthCredentialsService(BaseService):
    """Encrypted OAuth config fragment for rclone drive/onedrive remotes."""

    TYPE = SERVICE_TYPE
    VERSION = "1.0.0"
    NAME = "Rclone OAuth Credentials"
    DESCRIPTION = "Encrypted OAuth credentials for rclone Drive and OneDrive mounts"
    ICON = "key-round"

    @property
    def provider(self) -> str:
        return normalize_provider(self.config.get("provider", ""))

    def _create_connection(self):
        if self.provider not in PROVIDERS:
            raise ServiceError(
                f"Unknown rclone OAuth provider '{self.config.get('provider', '')}'. "
                f"Supported: {', '.join(PROVIDERS)}")
        return {"provider": self.provider, "ready": True}

    def _close_connection(self):
        return None

    def get_parameter_schema(self) -> Dict[str, Any]:
        return {
            "provider": {
                "type": "select",
                "required": True,
                "default": "drive",
                "options": list(PROVIDERS),
                "description": "Rclone OAuth backend whose credentials are stored here",
            },
            "label": {
                "type": "string",
                "default": "",
                "description": "Optional display label for this credential set",
            },
            "rclone_config": {
                "type": "textarea",
                "required": False,
                "sensitive": True,
                "description": "Encrypted rclone config body generated by Login via server or pasted manually, without the [remote] header",
            },
        }

    def get_parameter_rules(self) -> list:
        return []

    def get_service_actions(self) -> list:
        return [
            {
                "id": "rclone_server_login",
                "label": "Login via server",
                "icon": "",
                "when": {"provider": ["drive", "onedrive"]},
                "server_action": "rclone_server_login",
                "flow": "rclone_login_server",
            },
        ]


ServiceFactory.register(RcloneOAuthCredentialsService)
