import * as dotenv from 'dotenv';
import path from 'path';
import { AlpacaConnector } from '../src/connectors/alpaca.js';

async function testExecution() {
    console.log('--- Alpaca Execution Test Start ---');
    dotenv.config({ path: path.resolve(process.cwd(), '.env') });

    console.log(`Config Key: ${process.env.ALPACA_API_KEY ? 'FOUND' : 'MISSING'}`);
    console.log(`Asset Class: ${process.env.ASSET_CLASS || 'NOT SET'}`);
    console.log(`Paper Trading: ${process.env.PAPER_TRADING}`);

    const connector = new AlpacaConnector();

    // We use BTC/USD specifically as it's a known crypto pair on Alpaca
    const symbolsToTest = ['BTC/USD', 'BTCUSD'];
    const side = 'buy';
    const qty = 0.001; // Approx $95 at $95k price. Minimum is $10.
    const type = 'market';

    for (const symbol of symbolsToTest) {
        try {
            console.log(`--- Testing order placement for ${symbol} ---`);
            const order = await connector.placeOrder(symbol, side, qty, type);
            if (order && order.id) {
                console.log(`✅ SUCCESS for ${symbol}: Order placed! Order ID: ${order.id}`);
                return; // Stop if success
            }
        } catch (error: any) {
            const errorDetails = error.response ? JSON.stringify(error.response.data) : (error.message || error);
            console.log(`❌ FAILED for ${symbol}: ${errorDetails}`);
        }
    }

    console.log('--- Alpaca Execution Test End ---');
}

testExecution().catch(err => {
    console.log('Test script crashed:', err);
});
