"""
FinClaw - Strategy YAML Specification
Defines the standard format for community-contributed strategies.
"""

# whale-strategy.yaml schema
SCHEMA_EXAMPLE = """
# FinClaw Strategy Definition
# This is the standard format for all strategies in the marketplace

apiVersion: whale/v1
kind: Strategy

metadata:
  name: golden-cross-momentum
  version: 1.0.0
  author: community-user
  description: >
    AI-enhanced golden cross strategy. Buys when SMA50 crosses above SMA200
    with momentum confirmation from RSI and MACD. Uses AI to assess
    macro conditions before executing.
  tags:
    - crypto
    - momentum
    - ai-enhanced
    - beginner-friendly
  license: MIT

spec:
  # Which assets this strategy supports
  assets:
    type: crypto  # crypto | equity | forex | multi
    symbols:
      - BTC
      - ETH
      - SOL

  # Timeframe
  timeframe: 1d  # 1m | 5m | 15m | 1h | 4h | 1d | 1w

  # AI agents to use (optional - strategies can be pure rule-based)
  agents:
    - value    # Warren Buffett style
    - momentum # Technical analysis
    # - sentiment  # News/social sentiment
    # - macro      # Macro economics
    # - quant      # Statistical analysis

  # Entry conditions
  entry:
    rules:
      - indicator: sma_cross
        fast: 50
        slow: 200
        direction: above  # golden cross

      - indicator: rsi
        period: 14
        condition: between
        min: 30
        max: 70

    # AI confirmation (optional)
    ai_confirm: true
    ai_min_confidence: 0.6

  # Exit conditions
  exit:
    take_profit: 0.15    # 15% profit target
    stop_loss: 0.05      # 5% stop loss
    trailing_stop: 0.03  # 3% trailing stop
    max_hold_days: 30    # Maximum holding period

  # Risk management
  risk:
    max_position_pct: 0.20      # Max 20% of portfolio per position
    max_positions: 5            # Max 5 simultaneous positions
    max_daily_loss_pct: 0.05    # Stop trading if down 5% in a day
    max_drawdown_pct: 0.15      # Stop trading if drawdown > 15%

  # Backtest configuration (for marketplace listing)
  backtest:
    period: 2024-01-01..2026-03-01
    initial_capital: 10000
    benchmark: BTC

# Performance (auto-generated by backtester)
performance:
  total_return: 0.47        # 47% total return
  annual_return: 0.22       # 22% annualized
  sharpe_ratio: 2.1
  sortino_ratio: 2.8
  max_drawdown: -0.12       # -12% max drawdown
  win_rate: 0.62            # 62% winning trades
  profit_factor: 1.85
  total_trades: 47
  avg_trade_duration: 8.5   # days
"""


import yaml
from dataclasses import dataclass, field
from typing import Optional


@dataclass
class StrategyMetadata:
    name: str
    version: str
    author: str
    description: str = ""
    tags: list[str] = field(default_factory=list)
    license: str = "MIT"


@dataclass
class EntryRule:
    indicator: str
    condition: str = "cross"
    params: dict = field(default_factory=dict)


@dataclass
class ExitConfig:
    take_profit: float = 0.10
    stop_loss: float = 0.05
    trailing_stop: Optional[float] = None
    max_hold_days: Optional[int] = None


@dataclass
class RiskConfig:
    max_position_pct: float = 0.20
    max_positions: int = 5
    max_daily_loss_pct: float = 0.05
    max_drawdown_pct: float = 0.15


@dataclass
class StrategySpec:
    """Parsed strategy specification"""
    metadata: StrategyMetadata
    assets: list[str]
    timeframe: str
    agents: list[str]
    entry_rules: list[EntryRule]
    exit: ExitConfig
    risk: RiskConfig
    ai_confirm: bool = True
    ai_min_confidence: float = 0.6

    @classmethod
    def from_yaml(cls, yaml_str: str) -> "StrategySpec":
        """Parse a whale-strategy.yaml file"""
        data = yaml.safe_load(yaml_str)

        metadata = StrategyMetadata(
            name=data["metadata"]["name"],
            version=data["metadata"]["version"],
            author=data["metadata"]["author"],
            description=data["metadata"].get("description", ""),
            tags=data["metadata"].get("tags", []),
        )

        spec = data["spec"]
        entry = spec.get("entry", {})
        exit_data = spec.get("exit", {})
        risk_data = spec.get("risk", {})

        return cls(
            metadata=metadata,
            assets=spec.get("assets", {}).get("symbols", []),
            timeframe=spec.get("timeframe", "1d"),
            agents=spec.get("agents", []),
            entry_rules=[
                EntryRule(
                    indicator=r["indicator"],
                    condition=r.get("condition", ""),
                    params={k: v for k, v in r.items() if k not in ("indicator", "condition")},
                )
                for r in entry.get("rules", [])
            ],
            exit=ExitConfig(
                take_profit=exit_data.get("take_profit", 0.10),
                stop_loss=exit_data.get("stop_loss", 0.05),
                trailing_stop=exit_data.get("trailing_stop"),
                max_hold_days=exit_data.get("max_hold_days"),
            ),
            risk=RiskConfig(
                max_position_pct=risk_data.get("max_position_pct", 0.20),
                max_positions=risk_data.get("max_positions", 5),
                max_daily_loss_pct=risk_data.get("max_daily_loss_pct", 0.05),
                max_drawdown_pct=risk_data.get("max_drawdown_pct", 0.15),
            ),
            ai_confirm=entry.get("ai_confirm", True),
            ai_min_confidence=entry.get("ai_min_confidence", 0.6),
        )
