"""Shared CLI runtime context injected into commands."""

from __future__ import annotations

from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass

from rich.console import Console

try:
    from shared import BackendClient
except ImportError:
    from cli._vendor.shared import BackendClient

from .clients import ClientFactory
from .config import CLIConfig, ConfigStore


@dataclass
class CLIContext:
    console: Console
    config_store: ConfigStore
    client_factory: ClientFactory

    def load_config(self) -> CLIConfig:
        return self.config_store.load()

    def save_config(self, config: CLIConfig) -> CLIConfig:
        return self.config_store.save(config)

    @contextmanager
    def client(self, config: CLIConfig | None = None) -> Iterator[BackendClient]:
        active_config = config or self.load_config()
        client = self.client_factory.build(active_config)
        try:
            yield client
        finally:
            close = getattr(client, "close", None)
            if callable(close):
                close()
