import { supabaseService } from '../src/services/SupabaseService.js';
import { ConnectorFactory } from '../src/connectors/factory.js';
import { config } from '../src/config/index.js';
import { SymbolMapper } from '../src/utils/symbolMapper.js';
import logger from '../src/utils/logger.js';

async function debug() {
    logger.info("--- Debugging Profiles & Positions ---");
    const profiles = await supabaseService.getActiveProfiles();
    const users = await supabaseService.getActiveUsers();

    logger.info(`Found ${profiles.length} active profiles and ${users.length} active users.`);

    for (const profile of profiles) {
        const user = users.find(u => u.user_id === profile.user_id);
        if (!user) continue;

        const userKey = config.PAPER_TRADING ? user.ALPACA_API_KEY : user.REAL_ALPACA_API_KEY;
        const userSecret = config.PAPER_TRADING ? user.ALPACA_SECRET_KEY : user.REAL_ALPACA_SECRET_KEY;

        if (userKey && userSecret) {
            try {
                const exchange = ConnectorFactory.getCustomConnector(config.EXECUTION_PROVIDER, userKey, userSecret);
                for (const symbol of config.SYMBOLS) {
                    const tradeSymbol = SymbolMapper.toTradeSymbol(symbol, config.EXECUTION_PROVIDER);
                    const pos = await exchange.getPosition(tradeSymbol);
                    if (pos) {
                        logger.info(`    ✅ FOUND ${symbol} (${tradeSymbol}) for profile ${profile.name}: ${pos.qty} @ ${pos.avg_entry_price}`);
                    }
                }
            } catch (e) { /* ignore */ }
        }
    }

    logger.info("--- Checking MASTER Account (from .env) ---");
    const masterKey = config.ALPACA_API_KEY;
    const masterSecret = config.ALPACA_API_SECRET;
    if (masterKey) {
        try {
            const exchange = ConnectorFactory.getCustomConnector(config.EXECUTION_PROVIDER, masterKey, masterSecret);
            for (const symbol of config.SYMBOLS) {
                const tradeSymbol = SymbolMapper.toTradeSymbol(symbol, config.EXECUTION_PROVIDER);
                const pos = await exchange.getPosition(tradeSymbol);
                if (pos) {
                    logger.info(`    ✅ FOUND ${symbol} (${tradeSymbol}) for MASTER Account: ${pos.qty} @ ${pos.avg_entry_price}`);
                }
            }
        } catch (e: any) {
            logger.info(`    ❌ Error checking Master Account: ${e.message}`);
        }
    }
}

debug();
