from typing import Any

from fastapi import APIRouter, Header, HTTPException

from config import settings
from models.companion_rules import CompanionRulesUpdate
from services.ninja_presence import mark_ninja_seen
from services.risk_manager import evaluate_trade_intent
from services.trading_stats import rules_snapshot
from services.user_settings import (
    apply_companion_rules,
    apply_session_settings,
    companion_rules_response,
    session_settings_response,
)

router = APIRouter(prefix="/rules", tags=["rules"])


@router.get("/status")
def rules_status(
    x_paychek_client: str | None = Header(default=None, alias="X-Paychek-Client"),
) -> dict[str, Any]:
    """État des règles de session, risque et limites du jour."""
    if x_paychek_client == "ninjatrader-addon":
        mark_ninja_seen()
    snapshot = rules_snapshot()
    decision = evaluate_trade_intent(
        action="buy",
        source="dashboard_status",
        log=False,
    )
    return {
        "execution_mode": settings.execution_mode,
        **snapshot,
        "can_trade": decision.allowed,
        "can_trade_reason": decision.reason,
    }


@router.get("/settings")
def get_companion_rules() -> dict[str, Any]:
    """Reglages discipline actifs (compagnon ou .env)."""
    return companion_rules_response()


@router.patch("/settings")
@router.post("/settings")
def patch_companion_rules(body: CompanionRulesUpdate) -> dict[str, Any]:
    """Met a jour les regles depuis le dashboard — persiste sur le PC."""
    try:
        return apply_companion_rules(body)
    except ValueError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc


@router.get("/session")
def get_session_settings() -> dict[str, Any]:
    """Alias legacy — preferer GET /rules/settings."""
    return session_settings_response()


@router.patch("/session")
def patch_session_settings(body: CompanionRulesUpdate) -> dict[str, Any]:
    """Alias legacy — preferer PATCH /rules/settings."""
    return apply_session_settings(body)
