<?php

namespace App\Services\Bot;

use App\Models\User;
use App\Services\FlatTrade\BrokerAccountResolver;
use App\Services\FlatTrade\FlatTradeClient;

class PositionSizer
{
    public function __construct(
        private FlatTradeClient $client,
        private BrokerAccountResolver $resolver,
    ) {}

    public function lotsForConfidence(User $user, float $confidence, array $rulebook): int
    {
        $levels = $rulebook['global_rules']['confidence_levels'] ?? [];
        $available = 20000.0;

        if ($this->resolver->bindTradingClient($this->client, $user)) {
            $limits = $this->client->getLimits();
            $available = (float) ($limits['cash'] ?? $user->brokerAccount?->available_balance ?? $available);
        } elseif ($user->brokerAccount?->is_connected) {
            $available = (float) $user->brokerAccount->available_balance;
        }

        $maxLots = max(1, (int) floor($available / 15000));

        if ($confidence >= ($levels['high_confidence'] ?? 80)) {
            return min($maxLots, 3);
        }

        if ($confidence >= ($levels['normal_trade'] ?? 65)) {
            return min($maxLots, 2);
        }

        return 1;
    }
}
