from typing import Any

from connectors.base import PlatformConnector
from core.engine import discipline_engine
from models.discipline import TradeCheckRequest
from models.platform import ConnectorStatus, IntegrationPhase, PlatformId, TradeIntent


class ManualConnector(PlatformConnector):
    """Entrees utilisateur — bouton « Puis-je trader ? », API discipline."""

    platform_id = PlatformId.MANUAL
    display_name = "Manual / Companion"

    def status(self) -> ConnectorStatus:
        return ConnectorStatus(
            platform=self.platform_id,
            name=self.display_name,
            phase=IntegrationPhase.DISCIPLINE,
            enabled=True,
            discipline_manual=True,
            discipline_auto=False,
            message="API /discipline/can-trade and /discipline/check",
        )

    async def handle_inbound(self, payload: dict[str, Any]) -> dict[str, Any]:
        body = TradeCheckRequest(
            ticker=str(payload.get("ticker") or "UNKNOWN"),
            action=str(payload.get("action") or "buy"),
            source=str(payload.get("source") or "manual"),
            strategy=payload.get("strategy"),
            risk_usd=(
                float(v)
                if (v := payload.get("risk_usd")) is not None and v != ""
                else None
            ),
        )
        decision = discipline_engine.check_manual(body)
        return {
            "ok": True,
            "platform": self.platform_id.value,
            "allowed": decision.allowed,
            "reason": decision.reason,
            "message": "OK — trading allowed" if decision.allowed else decision.reason,
            **discipline_engine.snapshot(),
        }

    def parse_intent(self, payload: dict[str, Any]) -> TradeIntent:
        return TradeIntent(
            platform=PlatformId.MANUAL,
            ticker=str(payload.get("ticker") or "UNKNOWN"),
            action=str(payload.get("action") or "buy"),
            source=str(payload.get("source") or "manual"),
            strategy=payload.get("strategy"),
            raw=payload,
        )
