const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');

// Configurações
const CAPSOLVER_API_KEY = 'CAP-F424C55AC7E0360F95AB48383D9A0FEBD7DD7BB358E39F21F4EA91CEFF923326';
const TURNSTILE_SITE_KEY = '0x4AAAAAAAWV7kjZLnydRbx6';
const TURNSTILE_PAGE_URL = 'https://veiculosmg.fazenda.mg.gov.br/buscar-renavam/';

const PROXY_CONFIG = {
    host: 'gate.nodemaven.com',
    port: 8080,
    username: 'pkscabelim_gmail_com-country-br-ipv4-true',
    password: 'xcy2s9jsob'
};

const renavam = '00688384404';

async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function solveTurnstile() {
    console.log("-> Resolvendo Turnstile...");
    try {
        const createResponse = await axios.post('https://api.capsolver.com/createTask', {
            clientKey: CAPSOLVER_API_KEY,
            task: {
                type: 'AntiTurnstileTaskProxyLess',
                websiteURL: TURNSTILE_PAGE_URL,
                websiteKey: TURNSTILE_SITE_KEY,
                metadata: { action: 'consulta-buscar-renavam' }
            }
        }, { timeout: 30000 });

        if (createResponse.data.errorId !== 0) {
            throw new Error(`CapSolver error: ${createResponse.data.errorDescription}`);
        }

        const taskId = createResponse.data.taskId;
        for (let i = 0; i < 20; i++) {
            await sleep(3000);
            const resultResponse = await axios.post('https://api.capsolver.com/getTaskResult', {
                clientKey: CAPSOLVER_API_KEY,
                taskId: taskId
            }, { timeout: 30000 });

            if (resultResponse.data.status === 'ready') {
                console.log("✅ Turnstile resolvido!");
                return resultResponse.data.solution.token;
            }
        }
        throw new Error('Timeout Turnstile');
    } catch (e) {
        console.error("❌ Erro no Turnstile:", e.message);
        return null;
    }
}

async function testMG() {
    console.log(`--- INICIANDO TESTE MG (Renavam: ${renavam}) ---`);
    
    const token = await solveTurnstile();
    if (!token) return;

    const sessionId = Math.random().toString(36).substring(2, 12);
    const proxyUrl = `http://${PROXY_CONFIG.username}-session-${sessionId}:${PROXY_CONFIG.password}@${PROXY_CONFIG.host}:${PROXY_CONFIG.port}`;
    const agent = new HttpsProxyAgent(proxyUrl);

    console.log("-> Consultando Fazenda MG...");
    try {
        const response = await axios.get(`https://veiculosmg.fazenda.mg.gov.br/api/extrato-debito/renavam/${renavam}/`, {
            headers: {
                'Token': token,
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'Referer': 'https://veiculosmg.fazenda.mg.gov.br/buscar-renavam/',
                'Accept': 'application/json, text/plain, */*',
                'Accept-Language': 'pt-BR,pt;q=0.9',
                'Origin': 'https://veiculosmg.fazenda.mg.gov.br'
            },
            httpsAgent: agent,
            proxy: false, 
            timeout: 50000
        });

        console.log("\n--- DEBUG DA CONEXÃO ---");
        console.log("HTTP Code: " + response.status);

        console.log("\n--- RESULTADO DA FAZENDA ---");
        console.log(JSON.stringify(response.data, null, 2));
    } catch (e) {
        console.log("\n--- ERRO NA CONEXÃO ---");
        if (e.response) {
            console.log("HTTP Code:", e.response.status);
            console.log("Dados do Erro:", e.response.data);
        } else {
            console.log("Mensagem:", e.message);
        }
    }
    console.log("\n---------------------------");
}

testMG();
