"""Trading context — instrument identity for LLM cognitive layer.

Dynamically resolves per-instrument trading context based on symbol classification.
No more hardcoded Gold/XAUUSD singleton.

Usage:
    from src.trading_context import get_trading_context
    ctx = get_trading_context("BTCUSD")
    prompt = f"You are ... for {ctx.role_identity_en} ..."
"""

from __future__ import annotations

from dataclasses import dataclass, field


@dataclass(frozen=True)
class TradingContext:
    """Instrument identity injected into every LLM prompt template."""

    symbol: str = "XAUUSD"
    asset_name: str = "Gold"
    display_name: str = "Gold vs US Dollar"
    category: str = "metal"
    characteristics: str = ""
    macro_drivers: str = ""
    dxy_relevant: bool = True
    correlation_pair_name: str = "DXY USD Index vs Gold"

    # ── prompt template variables ──────────────────────────────

    @property
    def role_identity_en(self) -> str:
        """English role identity for system/user prompts."""
        return f"{self.asset_name} ({self.symbol})"

    @property
    def role_identity_cn(self) -> str:
        """Chinese role identity for system/user prompts."""
        return f"{self.symbol}"


# ── Dynamic context factory (no more singleton) ──

_CONTEXT_CACHE: dict[str, TradingContext] = {}


def get_trading_context(symbol: str = None) -> TradingContext:
    """Return a per-instrument TradingContext. Auto-detects symbol if None."""
    if not symbol:
        try:
            from bridge.gold_trader import _detect_active_symbol
            symbol = _detect_active_symbol()
        except Exception:
            symbol = "XAUUSD"
    symbol = str(symbol).strip().upper()

    if symbol in _CONTEXT_CACHE:
        return _CONTEXT_CACHE[symbol]

    from src.symbol_resolver import classify_symbol
    meta = classify_symbol(symbol)

    ctx = TradingContext(
        symbol=symbol,
        asset_name=symbol,
        display_name=symbol,
        category=meta.get("category", "commodity"),
        characteristics=meta.get("characteristics", ""),
        macro_drivers=meta.get("macro_drivers", ""),
        dxy_relevant=meta.get("dxy_relevant", False),
        correlation_pair_name=(
            "DXY USD Index vs Gold" if meta.get("dxy_relevant")
            else f"{symbol} (no DXY correlation)"
        ),
    )
    _CONTEXT_CACHE[symbol] = ctx
    return ctx
