"""
CV6 AI Trading OS — Paper Trading Router
Endpoints: /paper/trade  /paper/account  /paper/history  /paper/cancel  /paper/reset
H-3 FIX: All endpoints now require JWT authentication via get_current_user.
MM-03 FIX: Completed SELL trades are written to SQLite trade_history so that
           the Trade History page and Dashboard PnL display real paper trading data.
"""
import time
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from app.paper_trading.paper_models import PaperTradeRequest, PaperCancelRequest
from app.paper_trading.paper_manager import PaperTradingManager
from app.core.dependencies import get_current_user
from app.database.session import get_db

router = APIRouter(prefix="/paper", tags=["Paper Trading"])
manager = PaperTradingManager()


@router.post("/trade")
def execute_paper_trade(
    request: PaperTradeRequest,
    _user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    result = manager.execute_trade(
        capital=request.capital,
        symbol=request.symbol,
        action=request.action,
        quantity=request.quantity,
        entry_price=request.entry_price,
        stop_loss=request.stop_loss,
        target_price=request.target_price,
    )

    # ── MM-03 FIX: persist completed paper SELL to SQLite ────────────
    # When a paper SELL succeeds, write a trade_history record so that
    # /history/ and Dashboard PnL reflect actual paper trading results.
    if result.get("success") and request.action.upper() == "SELL" and "_sell_pnl" in result:
        try:
            from app.history.history_service import history_service
            from app.history.history_schemas import TradeCreate
            history_service.create(db, TradeCreate(
                broker="paper",
                symbol=request.symbol.upper(),
                exchange="NSE",
                trade_type="SELL",
                status="EXECUTED",
                quantity=result["_exit_quantity"],
                price=result["_exit_price"],
                avg_price=result["_exit_price"],
                filled_qty=result["_exit_quantity"],
                product="MIS",
                order_type="MARKET",
                pnl=result["_sell_pnl"],
                charges=0.0,
                notes=f"Paper trade: BUY@{result['_buy_price']} -> SELL@{result['_exit_price']}",
                placed_at=time.time(),
            ))
        except Exception as e:
            # Non-fatal: paper trade still succeeded even if DB write fails
            from loguru import logger
            logger.warning(f"[PaperRouter] Failed to persist trade to history: {e}")

        # Strip internal keys from API response
        result.pop("_sell_pnl", None)
        result.pop("_buy_price", None)
        result.pop("_exit_price", None)
        result.pop("_exit_quantity", None)

    return result


@router.get("/account")
def get_paper_account(_user=Depends(get_current_user)):
    """Full paper account snapshot: capital, positions, PnL, win rate."""
    return manager.account()


@router.get("/history")
def get_paper_history(_user=Depends(get_current_user)):
    """All closed paper trades."""
    return {"trades": manager.history()}


@router.post("/cancel")
def cancel_paper_position(request: PaperCancelRequest, _user=Depends(get_current_user)):
    """Cancel / close an open paper position at entry price."""
    return manager.cancel_position(request.symbol)


@router.post("/reset")
def reset_paper_account(capital: float = 100000.0, _user=Depends(get_current_user)):
    """Reset paper account to initial capital."""
    return manager.reset(capital)
