from typing import Any

from fastapi import APIRouter

from connectors.registry import connector_registry
from models.companion_rules import CompanionRulesUpdate
from models.discipline import TradeCheckRequest
from models.platform import PlatformId
from services.discipline_log import discipline_log
from services.user_settings import apply_companion_rules, companion_rules_response

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


@router.get("/can-trade")
async def can_trade(
    ticker: str = "UNKNOWN",
    action: str = "buy",
    source: str = "manual",
    risk_usd: float | None = None,
) -> dict[str, Any]:
    """« Puis-je trader ? » — entree manuelle (connecteur manual)."""
    connector = connector_registry.get(PlatformId.MANUAL)
    assert connector is not None
    payload: dict[str, Any] = {
        "ticker": ticker,
        "action": action,
        "source": source,
    }
    if risk_usd is not None:
        payload["risk_usd"] = risk_usd
    return await connector.handle_inbound(payload)


@router.post("/check")
async def check_trade(body: TradeCheckRequest) -> dict[str, Any]:
    connector = connector_registry.get(PlatformId.MANUAL)
    assert connector is not None
    return await connector.handle_inbound(body.model_dump())


@router.get("/events")
def discipline_events(limit: int = 50) -> dict[str, Any]:
    events = discipline_log.list_events(limit=limit)
    return {
        "count": len(events),
        "events": [e.model_dump(mode="json") for e in events],
    }


@router.get("/settings")
def get_discipline_settings() -> dict[str, Any]:
    """Reglages discipline — alias de GET /rules/settings."""
    return companion_rules_response()


@router.patch("/settings")
@router.post("/settings")
def patch_discipline_settings(body: CompanionRulesUpdate) -> dict[str, Any]:
    """Met a jour les regles depuis le dashboard."""
    return apply_companion_rules(body)
