"""Playbook Registry — 策略參數、藍圖、投資組合的集中管理與註冊機制。

Quick Start:
    from tradepose_client.registry import PlaybookRegistry, get_registry
    from tradepose_models.strategy import StrategyParams

    registry = get_registry()

    @registry.blueprint(config)
    def my_blueprint() -> list[Blueprint]:
        return BlueprintBuilder.sweep(config, entry_multipliers=[0.3], exit_sl=[4.25])

    @registry.portfolio("us100_balanced", capital=Decimal("100000"))
    def us100_balanced() -> list[tuple[str, str]]:
        return [(config.name, "L_fav_0.3__sl4.25_ts7_tp11")]
"""

from pathlib import Path

from .core import PlaybookRegistry
from .types import BpFactoryRecord

# Module-level singleton (lazy init)
_registry: PlaybookRegistry | None = None


def get_registry(root: str | Path | None = None) -> PlaybookRegistry:
    """取得全域 registry singleton。

    首次呼叫時依 root 路徑初始化，並自動建立 strategies/、blueprints/、portfolios/
    目錄結構。若傳入與已初始化路徑不同的 root，會重新初始化。

    Args:
        root: playbook 根目錄路徑（相對於 cwd 或絕對路徑，預設 "playbook"）。

    Returns:
        PlaybookRegistry singleton 實例。
    """
    global _registry
    resolved = Path(root).resolve() if root is not None else Path("playbook").resolve()
    if _registry is None or _registry._root != resolved:
        _registry = PlaybookRegistry(root=resolved)
        _registry.discover()
    return _registry


__all__ = [
    "PlaybookRegistry",
    "BpFactoryRecord",
    "get_registry",
]
