"""Hard risk rules in plain code. The AI cannot change or argue with these."""
from .config import ROOT

KILL_FILE = ROOT / "KILL"


class Risk:
    def __init__(self, cfg):
        self.c = cfg["risk"]

    @staticmethod
    def killed():
        return KILL_FILE.exists()

    def allowed(self, equity, day_start_equity, now, last_loss_time=None):
        if self.killed():
            return False, "kill switch is on"
        if day_start_equity and (day_start_equity - equity) / day_start_equity * 100 >= self.c["max_daily_loss_pct"]:
            return False, "daily loss limit reached"
        if last_loss_time is not None:
            mins = (now - last_loss_time).total_seconds() / 60
            if mins < self.c["cooldown_minutes"]:
                return False, "cooling down after a loss"
        return True, ""

    def size(self, equity, entry, stop_distance, params, broker=None, symbol=None, side=None):
        """Returns (qty, loss_per_unit). qty is sized so that hitting the stop loses risk_pct of the account.
        If the broker can price the loss exactly (MT5: any currency pair), it does; otherwise price distance is used."""
        if stop_distance <= 0 or entry <= 0 or equity <= 0:
            return 0.0, 0.0
        unit_loss = (broker.loss_per_unit(symbol, side, entry, stop_distance) if broker else None) or stop_distance
        qty = equity * params["risk_pct"] / unit_loss
        cap = broker.max_qty(symbol, side, entry, equity, self.c["max_leverage"]) if broker else None
        if cap is None:
            cap = equity * self.c["max_leverage"] / entry
        return min(qty, cap), unit_loss
