<?php

namespace App\Console\Commands;

use App\Models\BotRuntimeState;
use App\Models\Instrument;
use App\Models\Position;
use App\Models\User;
use App\Services\Bot\ExitEngine;
use App\Services\Bot\PositionMonitorService;
use App\Services\Bot\PositionSyncService;
use Illuminate\Console\Command;

class BotMonitorCommand extends Command
{
    protected $signature = 'bot:monitor {--once : Run one monitor cycle}';

    protected $description = 'Monitor open positions and evaluate exit rules';

    public function handle(
        PositionSyncService $positionSync,
        ExitEngine $exitEngine,
    ): int {
        $this->info('Position monitor started');

        do {
            BotRuntimeState::heartbeat('bot_monitor', 'running');

            $users = User::whereHas('positions', fn ($q) => $q->where('is_open', true))
                ->with(['strategy', 'brokerAccount', 'positions.instrument'])
                ->get();

            foreach ($users as $user) {
                $positionSync->syncUser($user);
                $rulebook = $user->strategy?->rulebook ?? config('rulebook');

                foreach ($user->positions->where('is_open', true) as $position) {
                    $ltp = (float) ($position->ltp ?: $position->instrument?->latestTick?->ltp ?: $position->net_avg_price);
                    $reason = $exitEngine->evaluate($position, $ltp, $rulebook);
                    if ($reason) {
                        $exitEngine->executeExit($user, $position, $reason, $rulebook);
                    }
                }
            }

            if ($this->option('once')) {
                break;
            }

            sleep(15);
        } while (true);

        return self::SUCCESS;
    }
}
