#!/usr/bin/env python3
import json
import os
import traceback
import sys
# Importamos a nossa trava de segurança do arquivo vizinho
from duckdb_engine import get_connection

def application(environ, start_response):
    # --- ROTA DE INTERFACE (VISUALIZAÇÃO NO CHROME) ---
    if environ.get('REQUEST_METHOD') == 'GET':
        start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
        return [f"""
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>LinkTudo - DuckDB Protected Engine</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {{ background: #0a0a0b; color: #ffff00; font-family: 'Consolas', monospace; padding: 20px; }}
        .test-box {{ background: #111; border: 1px solid #333; padding: 20px; border-radius: 12px; margin-bottom: 15px; border-left: 5px solid #00ff00; }}
        .btn-run {{ background: transparent; color: #ffff00; border: 2px solid #ffff00; font-weight: bold; padding: 10px; cursor: pointer; }}
        .btn-run:hover {{ background: #ffff00; color: #000; }}
        .btn-copy {{ background: #ffff00; color: #000; font-weight: bold; width: 100%; padding: 15px; border: none; border-radius: 8px; margin-top: 10px; cursor: pointer; }}
        pre {{ background: #000; color: #ffff00; padding: 10px; border: 1px solid #222; font-size: 11px; max-height: 400px; overflow: auto; }}
        .shield {{ color: #00ff00; font-size: 12px; margin-bottom: 10px; font-weight: bold; }}
    </style>
</head>
<body>
    <div class="container" style="max-width: 800px;">
        <h3 style="font-weight: 900;">⚡ DUCKDB ENGINE PROTEGIDO</h3>
        <p class="text-muted">Limites ativos: 1 Core / 128MB RAM (via duckdb_engine.py)</p>
        
        <div class="test-box">
            <div class="shield">🛡️ HARDWARE LIMITER STATUS: ATIVO</div>
            <h6>SCANNER GERAL DE ARQUIVO PARQUET (3.6GB)</h6>
            <p class="small text-muted">A execução será feita em thread única para não derrubar o Passenger.</p>
            <button onclick="runTests()" class="btn btn-run">EXECUTAR SCANNER AGORA</button>
            <pre id="out-main" class="mt-3 d-none"></pre>
        </div>

        <button onclick="copyToClipboard()" class="btn btn-copy">📋 COPIAR DIAGNÓSTICO PARA O GEMINI</button>
        <div id="msg-copy" class="text-center mt-2 small" style="display:none; color: #fff;">Copiado para a área de transferência!</div>
    </div>

    <script>
    let diagnosticResult = "Aguardando execução...";
    async function runTests() {{
        const out = document.getElementById('out-main');
        out.classList.remove('d-none');
        out.innerText = 'DuckDB está processando o arquivo com limites rígidos...';
        
        try {{
            const r = await fetch('', {{
                method: 'POST',
                headers: {{'Content-Type': 'application/json'}},
                body: JSON.stringify({{action: 'diagnostico_geral'}})
            }});
            const data = await r.json();
            diagnosticResult = JSON.stringify(data, null, 4);
            out.innerText = diagnosticResult;
        }} catch(e) {{
            out.innerText = "ERRO: O servidor excedeu o tempo ou a RAM foi cortada.";
        }}
    }}

    function copyToClipboard() {{
        navigator.clipboard.writeText("DIAGNOSTICO_BLINDADO_V2:\\n" + diagnosticResult);
        const msg = document.getElementById('msg-copy');
        msg.style.display = 'block';
        setTimeout(() => msg.style.display = 'none', 2000);
    }}
    </script>
</body>
</html>
""".encode('utf-8')]

    # --- ROTA DE PROCESSAMENTO (POST) ---
    if environ.get('REQUEST_METHOD') == 'POST':
        start_response('200 OK', [('Content-Type', 'application/json; charset=utf-8')])
        try:
            path = "/home/link6350/arquivos_restritos/banco_de_dados/parquet/cnpj/tabelas_auxiliares_pesadas/cnpj___tb_aux___estabelecimentos___por_cnae_por_logradouro___mais_agregacoes___para_filtro_personalizado___cliente_final.parquet"
            
            # CHAVE DE SEGURANÇA: Obtém a conexão já limitada
            con = get_connection()

            # Processamento otimizado
            count_total = con.execute(f"SELECT count(*) FROM read_parquet('{path}')").fetchone()[0]
            count_4733 = con.execute(f"SELECT count(*) FROM read_parquet('{path}') WHERE municipio_codigo = '4733'").fetchone()[0]
            cols_info = con.execute(f"DESCRIBE SELECT * FROM read_parquet('{path}') LIMIT 0").fetchall()
            colunas = [row[0] for row in cols_info]

            return [json.dumps({
                "status": "sucesso_blindado",
                "configuracao": "1_core_128mb_limit",
                "total_linhas": count_total,
                "municipio_4733": count_4733,
                "colunas": colunas,
                "engine_file": "duckdb_engine.py"
            }).encode('utf-8')]

        except Exception as e:
            return [json.dumps({
                "status": "error", 
                "msg": str(e), 
                "trace": traceback.format_exc()
            }).encode('utf-8')]

    return [b"Metodo nao permitido"]