import sys
import os
import subprocess
from fasthtml.common import *
from starlette.responses import FileResponse

# Importa a lógica de pesquisa
from pesq_cp1 import buscar_produto, render_tabela
from pesq_cl1 import buscar_cliente, render_tabela_cl1
from pesq_vd1 import buscar_vendedor, render_tabela_vd1

# Estilos personalizados
css_personalizado = Style("""
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');

/* Força o cursor de carregamento em toda a tela durante o processamento do HTMX */
    body.htmx-request, body.htmx-request * {
        cursor: wait !important;
    }

    html, body, button, input, select, textarea, table, th, td, h1, h2, h3, h4, h5, h6 {
        font-family: 'Roboto', sans-serif !important;
    }

* {
    font-family: 'Roboto', sans-serif;
}

body {
    overflow-x: hidden;
}
    .modal-overlay {
        position: fixed; 
        top: 0; 
        left: 0; 
        width: 100vw; 
        height: 100vh;
        background: rgba(0, 0, 0, 0.6); 
        display: flex;
        align-items: center; 
        justify-content: center; 
        z-index: 1000;
        padding: 0; /* Removido qualquer espaçamento externo */
    }
    .modal-content {
        background: white; 
        padding: 20px; 
        border-radius: 0; /* Opcional: bordas retas ficam melhores em 100% */
        width: 100vw; 
        height: 100vh;
        max-width: 100%; 
        max-height: 100%; 
        overflow-y: auto;
        box-sizing: border-box; /* Garante que o padding não estoure a tela */
    }
""")

# Importação da fonte via CDN do Google Fonts
font_roboto = Link(
    rel="stylesheet",
    href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
)

# Ao instanciar o app, passe o link da fonte e o CSS nos hdrs (headers)
app, router = fast_app(
    hdrs=(font_roboto, css_personalizado)
)

@router("/")
def principal():
    return Title("Consulta Banco PS"), Main(
        # Header flexível: Alinha a Logo e o Título lado a lado
        Header(
            # Coluna 1 (Esquerda): Logo
            Div(
                Img(
                    src="/logoia.jpg", 
                    width="80", 
                    cls="img-fluid", 
                    style="height: auto; border-radius: 10px;"
                ),
                style="display: flex; justify-content: flex-start;"
            ),
            # Coluna 2 (Centro): Pergunta
            Div(
                H3(
                    "Qual é a sua pergunta ao Banco de Dados da PS?", 
                    style="color: #0D6EFD; margin: 0; text-align: center;"
                ),
                style="display: flex; justify-content: center; align-items: center;"
            ),
            # Coluna 3 (Direita): Espaçador para manter a pergunta 100% centralizada na tela
            Div(style="width: 80px;"),
            style="display: grid; grid-template-columns: auto 1fr auto; align-items: center; margin-top: 1rem; margin-bottom: 2rem;"
        ),
        # Form Principal
        Form(
            Fieldset(
                Input(
                    id="campo-pergunta",
                    name="nome", 
                    placeholder="Digite sua pergunta...", 
                    required=True, 
                    autofocus=True 
                ),
                Button("Enviar", type="submit"),
                # Botão para abrir a busca eventual de produtos
                Button(
                    "🔍 Pesquisar Produto", 
                    type="button",
                    cls="secondary outline",
                    style="margin-left: 10px;",
                    hx_get="/modal-pesquisa",
                    hx_target="#container-modal",
                    hx_swap="innerHTML"
                ),
                Button(
                    "🔍 Pesquisar Cliente", 
                    type="button",
                    cls="secondary outline",
                    style="margin-left: 10px;",
                    hx_get="/modal-pesquisa-cliente",
                    hx_target="#container-modal",
                    hx_swap="innerHTML"
                ),
                Button(
                    "🔍 Pesquisar Vendedor", 
                    type="button",
                    cls="secondary outline",
                    style="margin-left: 10px;",
                    hx_get="/modal-pesquisa-vendedor",
                    hx_target="#container-modal",
                    hx_swap="innerHTML"
                )
            ),
            hx_post="/resultado",
            hx_target="#resultado",
            hx_swap="innerHTML",
            hx_indicator="body"
        ),
        
        # Regiões de resultado e modal
        Div(id="resultado"),
        Div(id="container-modal"),
        cls="container"
    )


# ============================================================
# ROTAS DO MODAL DE PESQUISA DE CLIENTES
# ============================================================

@router("/modal-pesquisa-cliente")
def modal_pesquisa_cliente():
    """Abre a janela para pesquisar clientes."""

    clientes = buscar_cliente("")

    return Div(
        Div(
            Header(
                Div(
                    Img(
                        src="/logoia.jpg",
                        width="80",
                        cls="img-fluid",
                        style="height: auto; border-radius: 10px;"
                    ),

                    H3(
                        "Pesquisa de Clientes",
                        style="margin: 0; color: #0D6EFD;"
                    ),

                    Button(
                        "✕",
                        onclick="document.getElementById('container-modal').innerHTML=''",
                        style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:red;"
                    ),

                    style="""
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        gap: 15px;
                        width: 100%;
                    """
                )
            ),

            Br(),

            Form(
                Input(
                    autofocus=True,
                    type="text",
                    name="busca",
                    placeholder="Digite o nome do cliente...",
                    hx_post="/buscar-cliente-modal",
                    hx_target="#tabela-modal-cliente",
                    hx_trigger="input changed delay:300ms"
                )
            ),

            Div(
                id="tabela-modal-cliente",
                children=render_tabela_cl1(clientes, "")
            ),

            cls="modal-content"
        ),
        cls="modal-overlay"
    )


@router("/buscar-cliente-modal", methods=["POST"])
def buscar_cliente_modal(busca: str = ""):
    """Pesquisa clientes dentro do modal."""

    clientes = buscar_cliente(busca)

    return render_tabela_cl1(clientes, busca)


@router("/selecionar-cliente")
def selecionar_cliente(codigo: str):
    """Insere o código do cliente no campo de pergunta e fecha o modal."""

    return Script(f"""
        document.getElementById('campo-pergunta').value += ' {codigo} ';
        document.getElementById('container-modal').innerHTML = '';
        document.getElementById('campo-pergunta').focus();
    """)
# ============================================================
# ROTAS DO MODAL DE PESQUISA DE VENDEDORES
# ============================================================

@router("/modal-pesquisa-vendedor")
def modal_pesquisa_vendedor():
    """Abre a janela para pesquisar vendedores."""

    vendedores = buscar_vendedor("")

    return Div(
        Div(
            Header(
                Div(
                    Img(
                        src="/logoia.jpg",
                        width="80",
                        cls="img-fluid",
                        style="height: auto; border-radius: 10px;"
                    ),

                    H3(
                        "Pesquisa de Vendedores",
                        style="margin: 0; color: #0D6EFD;"
                    ),

                    Button(
                        "✕",
                        onclick="document.getElementById('container-modal').innerHTML=''",
                        style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:red;"
                    ),

                    style="""
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        gap: 15px;
                        width: 100%;
                    """
                )
            ),

            Br(),

            Form(
                Input(
                    autofocus=True,
                    type="text",
                    name="busca",
                    placeholder="Digite o nome do vendedor...",
                    hx_post="/buscar-vendedor-modal",
                    hx_target="#tabela-modal-vendedor",
                    hx_trigger="input changed delay:300ms"
                )
            ),

            Div(
                id="tabela-modal-vendedor",
                children=render_tabela_vd1(vendedores, "")
            ),

            cls="modal-content"
        ),
        cls="modal-overlay"
    )


@router("/buscar-vendedor-modal", methods=["POST"])
def buscar_vendedores_modal(busca: str = ""):
    """Pesquisa vendedores dentro do modal."""

    vendedores = buscar_vendedor(busca)

    return render_tabela_vd1(vendedores, busca)


@router("/selecionar-vendedor")
def selecionar_vendedor(codigo: str):
    """Insere o código do vendedor no campo de pergunta e fecha o modal."""

    return Script(f"""
        document.getElementById('campo-pergunta').value += ' {codigo} ';
        document.getElementById('container-modal').innerHTML = '';
        document.getElementById('campo-pergunta').focus();
    """)

# --- ROTAS DO MODAL DE PESQUISA (pesq_cp1.py) ---

@router("/modal-pesquisa")
def modal_pesquisa():
    """Abre a janela flutuante para pesquisar produtos na tabela produtoia."""
    produtos = buscar_produto("")
    return Div(
        Div(
            Header(
               Div(
                  Img(
                      src="/logoia.jpg", 
                      width="80", 
                      cls="img-fluid", 
                      style="height: auto; border-radius: 10px;"
                      ),
                  H3("Pesquisa de Produtos", style="margin: 0; color: #0D6EFD;"),
                  Button(
                      "✕", 
                      onclick="document.getElementById('container-modal').innerHTML=''", 
                      style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:red;"
                  ),
                  style="display: flex; align-items: center; justify-content: space-between; gap: 15px; width: 100%;"
            )),
            Br(),
            Form(
                Input(
                    autofocus=True,
                    type="text", 
                    name="busca", 
                    placeholder="Digite o nome do produto...",
                    hx_post="/buscar-produto-modal",
                    hx_target="#tabela-modal",
                    hx_trigger="input changed delay:300ms"
                )
            ),
            Div(id="tabela-modal", children=render_tabela(produtos, "")),
            cls="modal-content"
        ),
        cls="modal-overlay"
    )

@router("/buscar-produto-modal", methods=["POST"])
def buscar_modal(busca: str = ""):
    produtos = buscar_produto(busca)
    return render_tabela(produtos, busca)

@router("/selecionar-codigo")
def selecionar_codigo(codigo: str):
    """Insere o código do produto no campo de pergunta e fecha a pesquisa."""
    return Script(f"""
        document.getElementById('campo-pergunta').value += ' {codigo} ';
        document.getElementById('container-modal').innerHTML = '';
        document.getElementById('campo-pergunta').focus();
    """)

# --- ROTAS DE PROCESSAMENTO E IA (grok.py) ---

@router("/resultado", methods=["POST"])
def resultado_post(nome: str):
    try:
        # Executa o script grok.py que consulta o Llama-3.3-70b-versatile
        processo = subprocess.run(
            [sys.executable, "grok.py", nome],
            capture_output=True,
            text=True,
            check=True,
            encoding="utf-8",
            errors="replace"
        )
        
        return Div(
            H4("--- Resposta do Processamento ---", style="color: #198754; margin-top: 20px;"),
            Div(
                A(
                    Img(
                        src="/excel.jpg", 
                        width="90", 
                        cls="img-fluid rounded-2 mx-3", 
                        style="cursor: pointer; margin: 0 1rem;"
                    ),
                    href="/download-excel", 
                    title="Clique para baixar a planilha"
                ),
                cls="d-flex justify-content-center my-3"
            ),
            Pre(processo.stdout, style="background-color: #f8f9fa; padding: 15px; border-radius: 5px;")
        )

    except subprocess.CalledProcessError as e:
        return Div(
            H4("Erro ao executar o script!", style="color: #dc3545; margin-top: 20px;"),
            Pre(
                e.stderr if e.stderr else e.stdout, 
                style="background-color: #f8d7da; color: #842029; padding: 15px; border-radius: 5px;"
            )
        )

@router("/download-excel")
def download_excel():
    arquivo = "resultado.xlsx"
    if os.path.exists(arquivo):
        return FileResponse(
            arquivo, 
            filename="resultado.xlsx", 
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
    return Div("Arquivo não encontrado no servidor.", style="color: red;")

serve()
