"""
activate_strategy / deactivate_strategy / list_active_strategies

paper=True  (default): forward paper trading — strategy runs on live data with
            simulated fills via PaperAccount.

paper=False: live trading — not yet implemented (requires secrets vault).

Each activated strategy runs in its own subprocess from a git worktree,
ensuring the production version is isolated from edits in the working tree.
Events (fills, PnL updates, errors) flow via ZMQ PUSH/PULL to EventPublisher.
"""

import json
import logging
from typing import Any

log = logging.getLogger(__name__)


async def activate_strategy(
    strategy_name: str,
    feeds: list[dict],
    allocation: float,
    paper: bool = True,
) -> list:
    """
    Activate a strategy for live or paper forward trading.

    Args:
        strategy_name: Display name as saved via PythonWrite("strategy", ...)
        feeds: List of feed dicts: [{"symbol": "BTC/USDT.BINANCE", "period_seconds": 3600}]
        allocation: Capital allocated in quote currency (e.g. 5000.0 USDT)
        paper: True = paper/simulated fills (default); False = live (not yet implemented)

    Returns:
        list[TextContent] with JSON:
        {"status": "activated", "strategy_name": str, "paper": bool, "allocation": float,
         "git_revision": str, "pid": int}
    """
    from mcp.types import TextContent

    def _err(msg: str) -> list:
        log.error("activate_strategy '%s': %s", strategy_name, msg)
        return [TextContent(type="text", text=json.dumps({"error": msg}))]

    if not paper:
        return _err(
            "Live trading (paper=False) requires the user secrets vault, "
            "which is not yet implemented. Use paper=True for paper forward testing."
        )

    if not feeds:
        return _err("feeds list is empty")

    for f in feeds:
        if not f.get("symbol"):
            return _err(f"Feed entry missing 'symbol': {f}")

    try:
        from dexorder.strategy.lifecycle import get_strategy_lifecycle
        lifecycle = get_strategy_lifecycle()
        result = await lifecycle.activate(
            strategy_name=strategy_name,
            feeds=feeds,
            allocation=allocation,
            paper=paper,
        )
    except Exception as exc:
        log.exception("activate_strategy: lifecycle activation failed")
        return _err(f"Activation failed: {exc}")

    if "error" in result:
        return _err(result["error"])

    return [TextContent(type="text", text=json.dumps(result))]


async def deactivate_strategy(strategy_name: str) -> list:
    """
    Deactivate a running strategy and return its final P&L summary.

    Returns:
        list[TextContent] with JSON:
        {"status": "deactivated", "strategy_name": str, "final_pnl": float}
    """
    from mcp.types import TextContent

    def _err(msg: str) -> list:
        log.error("deactivate_strategy '%s': %s", strategy_name, msg)
        return [TextContent(type="text", text=json.dumps({"error": msg}))]

    try:
        from dexorder.strategy.lifecycle import get_strategy_lifecycle
        lifecycle = get_strategy_lifecycle()
        result = await lifecycle.deactivate(strategy_name)
    except Exception as exc:
        log.exception("deactivate_strategy: failed")
        return _err(f"Deactivation failed: {exc}")

    if "error" in result:
        return _err(result["error"])

    return [TextContent(type="text", text=json.dumps(result))]


async def list_active_strategies() -> list:
    """
    Return a list of currently active strategies with PnL state.

    Returns:
        list[TextContent] with JSON:
        {"active_strategies": [{strategy_name, paper, allocation, feeds, realized_pnl, ...}]}
    """
    from mcp.types import TextContent

    try:
        from dexorder.strategy.lifecycle import get_strategy_lifecycle
        lifecycle = get_strategy_lifecycle()
        active = await lifecycle.list_active()
    except Exception as exc:
        log.exception("list_active_strategies: failed")
        active = []

    return [TextContent(type="text", text=json.dumps({"active_strategies": active}))]
