"""TradePose Python Client SDK.

Quick Start:
    import polars as pl
    from tradepose_client import (
        # Enums - 策略定義
        EntryType, Freq, IndicatorType, OrderStrategy, TradeDirection, TrendType,
        # Strategy Builder - 建立策略配置
        StrategyBuilder, BlueprintBuilder, TradingContext,
        # Sweep Helpers - 參數掃描
        frange, be_range,
        # Batch Testing - 回測執行
        BatchTester, Period,
        # Trading Setup - 實盤部署
        TradingSetup,
    )

    # 連線設定
    API_KEY = "sk_xxx"
    SERVER_URL = "https://api.tradepose.com"
    tester = BatchTester(api_key=API_KEY, server_url=SERVER_URL)

    # Step 0 - 建立策略配置（詳見 StrategyBuilder 文件）
    builder = StrategyBuilder(name="my_strategy", base_instrument="US100", base_freq="1h")
    atr = builder.add_indicator("atr", period=14, freq=Freq.DAY_1, shift=1)
    base_bp = (
        BlueprintBuilder("base", TradeDirection.LONG, TrendType.TREND)
        .add_immediate_entry_trigger(conditions=[...])
        .build()
    )
    strategy = builder.set_base_blueprint(base_bp).build(volatility_indicator=atr)

    # 參數掃描 - 產生多個 delay entry blueprints
    adv_blueprints = BlueprintBuilder.sweep_delay_entry(
        direction=TradeDirection.LONG,
        distance_expr=atr.col(),
        multipliers=frange(0.1, 0.5, 0.1),  # [None, 0.1, 0.2, 0.3, 0.4, 0.5]
        entry_type=EntryType.FAVORABLE,     # 預設值，可省略
    )

    # Step 1 - 提交回測
    batch = tester.submit(
        strategies=[strategy],
        periods=[Period.from_year(2024)],
    )

    # Step 2 - 查看結果摘要
    batch.summary("pnl_pct")  # 依 pnl_pct 排序的績效摘要
    batch.all_trades()        # 所有交易明細

    # Step 3 - 進階分析 (MAE/MFE)
    analyzer = batch.analyzer()

    # 篩選特定 blueprint（設定 metric_col, normalize 後續方法自動套用）
    opts = [i for i in analyzer.available_blueprints().options
            if "L_adv_0.4__sl1.5_ts1.5" in i.value]
    scope = analyzer.build_scope(opts[0], metric_col="pnl_pct", normalize=True)

    # 績效與圖表（自動使用預設值）
    scope.performance()                    # 使用預設 metric_col
    scope.plot_equity()                    # 使用預設 metric_col
    scope.plot_scatter(x="mae", y="g_mfe") # 預設 normalize=True（除以 volatility）

    # Step 4 - 取得 OHLCV 資料
    # 基礎 OHLCV（含指標）
    ohlcv = tester.submit_ohlcv(strategy=strategy, period=Period.from_year(2024))

    # Enhanced OHLCV（含交易標記，用於除錯）
    enhanced = tester.submit_enhanced_ohlcv(
        strategy=strategy,
        period=Period.from_year(2024),
        strategy_name=strategy.name,
        blueprint_name="L_adv_0.4__sl1.5_ts1.5",
    )

    # Step 5 - 實盤部署
    setup = TradingSetup(api_key=API_KEY, server_url=SERVER_URL)
"""

# Import enums from tradepose_models for convenient access
from tradepose_models.enums import (
    EntryType,
    Freq,
    IndicatorType,
    OrderStrategy,
    TradeDirection,
    TrendType,
)

# Analysis API
from .analysis import (
    ChartConfig,
    MAEMFEAnalyzer,
    MAEMFEStatistics,
)

# Batch testing API
from .batch import (
    BacktestRequest,
    BatchResults,
    BatchTester,
    Period,
    PeriodResult,
)
from .builder import (
    BlueprintBuilder,
    StrategyBuilder,
    TradingContext,
    be_range,
    frange,
)
from .client import TradePoseClient
from .config import TradePoseConfig
from .exceptions import (
    AuthenticationError,
    AuthorizationError,
    NetworkError,
    RateLimitError,
    ResourceNotFoundError,
    SerializationError,
    ServerError,
    StrategyError,
    SubscriptionError,
    TaskCancelledError,
    TaskError,
    TaskFailedError,
    TaskTimeoutError,
    TradePoseAPIError,
    TradePoseConfigError,
    TradePoseError,
    ValidationError,
)

# Trading Setup (sync wrapper)
from .setup import TradingSetup

__version__ = "1.5.0"

__all__ = [
    # Main client
    "TradePoseClient",
    "TradePoseConfig",
    # Base exceptions
    "TradePoseError",
    "TradePoseConfigError",
    "TradePoseAPIError",
    # API exceptions
    "AuthenticationError",
    "AuthorizationError",
    "ResourceNotFoundError",
    "ValidationError",
    "RateLimitError",
    "ServerError",
    "NetworkError",
    # Task exceptions
    "TaskError",
    "TaskTimeoutError",
    "TaskFailedError",
    "TaskCancelledError",
    # Data exceptions
    "SerializationError",
    # Business logic exceptions
    "SubscriptionError",
    "StrategyError",
    # Builder classes
    "StrategyBuilder",
    "BlueprintBuilder",
    "TradingContext",
    "frange",
    "be_range",
    # Trading Setup (sync wrapper)
    "TradingSetup",
    # Batch testing API
    "BatchTester",
    "BatchResults",
    "PeriodResult",
    "Period",
    "BacktestRequest",
    # Analysis API
    "MAEMFEAnalyzer",
    "MAEMFEStatistics",
    "ChartConfig",
    # Enums (for convenient strategy building)
    "EntryType",
    "Freq",
    "IndicatorType",
    "OrderStrategy",
    "TradeDirection",
    "TrendType",
]
