from __future__ import annotations

from pathlib import Path
from typing import Any

from niannian.storage.cloud_base import CloudBackend, FileCloudBackend, HttpOpener
from niannian.storage.feimao_live import FeimaoLiveBackend, build_feimao_backend


class FeimaoBackend:
    """飞猫盘 L1 — session_token 鉴权；live 或 mirror MVP。"""

    def __init__(
        self,
        root: Path,
        *,
        session_token: str | None = None,
        force_mirror: bool = True,
        live: bool = False,
        api_base: str | None = None,
        http_opener: HttpOpener | None = None,
        credential_manager: Any | None = None,
        **kwargs: Any,
    ) -> None:
        self._delegate: CloudBackend = build_feimao_backend(
            root,
            session_token=session_token,
            force_mirror=force_mirror,
            live=live,
            api_base=api_base,
            http_opener=http_opener,
            credential_manager=credential_manager,
            **kwargs,
        )

    @property
    def name(self) -> str:
        return self._delegate.name

    @property
    def root(self) -> Path:
        return self._delegate.root

    @property
    def token(self) -> str | None:
        delegate = self._delegate
        if isinstance(delegate, FileCloudBackend):
            return delegate.token
        if isinstance(delegate, FeimaoLiveBackend):
            return delegate.token
        return None

    @property
    def last_upload_degraded(self) -> bool:
        return bool(getattr(self._delegate, "last_upload_degraded", False))

    def is_configured(self) -> bool:
        return self._delegate.is_configured()

    def status(self) -> str:
        return self._delegate.status()

    def primary_mode(self) -> str:
        return self._delegate.primary_mode()

    def upload(self, rel_path: str, data: bytes) -> bool:
        return self._delegate.upload(rel_path, data)

    def download(self, rel_path: str) -> bytes | None:
        return self._delegate.download(rel_path)
