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

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

const CAPSOLVER_API_KEY = 'CAP-F424C55AC7E0360F95AB48383D9A0FEBD7DD7BB358E39F21F4EA91CEFF923326';

function getProxyAgent(sessionId = null) {
    let username = PROXY_CONFIG.username;
    if (sessionId) username = `${PROXY_CONFIG.username}-session-${sessionId}`;
    const proxyUrl = `http://${username}:${PROXY_CONFIG.password}@${PROXY_CONFIG.host}:${PROXY_CONFIG.port}`;
    return new HttpsProxyAgent(proxyUrl);
}

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

/**
 * Consulta MS (via API Externa)
 */
async function consultarMS(placa, renavam) {
    const url = `http://52.15.37.114/dk/api.php?placa=${placa}&renavam=${renavam}`;
    try {
        const agent = getProxyAgent();
        const response = await axios.get(url, { 
            httpAgent: agent, 
            httpsAgent: agent,
            timeout: 30000 
        });
        return response.data;
    } catch (e) {
        return { success: false, error: e.message };
    }
}

/**
 * Resolve Turnstile para MG
 */
async function solveMGTurnstile() {
    try {
        const createResponse = await axios.post('https://api.capsolver.com/createTask', {
            clientKey: CAPSOLVER_API_KEY,
            task: {
                type: 'AntiTurnstileTaskProxyLess',
                websiteURL: 'https://veiculosmg.fazenda.mg.gov.br/buscar-renavam/',
                websiteKey: '0x4AAAAAAAWV7kjZLnydRbx6',
                metadata: { action: 'consulta-buscar-renavam' }
            }
        });

        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
            });
            if (resultResponse.data.status === 'ready') return resultResponse.data.solution.token;
        }
    } catch (e) {
        console.error("Erro Turnstile MG:", e.message);
    }
    return null;
}

/**
 * Consulta MG (Direto na Fazenda)
 */
async function consultarMG(renavam) {
    const token = await solveMGTurnstile();
    if (!token) return { success: false, error: "Falha ao resolver captcha MG" };

    const sessionId = Math.random().toString(36).substring(2, 12);
    const agent = getProxyAgent(sessionId);

    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, */*',
                'Origin': 'https://veiculosmg.fazenda.mg.gov.br'
            },
            httpsAgent: agent,
            timeout: 50000
        });
        return { success: true, data: response.data };
    } catch (e) {
        return { success: false, error: e.response ? e.response.data : e.message };
    }
}

module.exports = { consultarMS, consultarMG };
