import sys
import os
import subprocess
from fasthtml.common import *
from starlette.responses import FileResponse

# Importação dos módulos 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
from pesq_po1 import buscar_posic, render_tabela_po1
from pesq_gru import buscar_grupo, render_tabela_gru

# Estilos personalizados
css_personalizado = Style("""
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');

    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;
    }
    .modal-content {
        background: white; 
        padding: 20px; 
        border-radius: 0; 
        width: 100vw; 
        height: 100vh;
        max-width: 100%; 
        max-height: 100%; 
        overflow-y: auto;
        box-sizing: border-box;
    }
""")

font_roboto = Link(
    rel="stylesheet",
    href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
)

app, router = fast_app(
    hdrs=(font_roboto, css_personalizado)
)

@router("/")
def principal():
    return Title("Consulta Banco PS"), Main(
        Header(
            Div(
                Img(
                    src="/logoia.jpg", 
                    width="80", 
                    cls="img-fluid", 
                    style="height: auto; border-radius: 10px;"
                ),
                style="display: flex; justify-content: flex-start;"
            ),
            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;"
            ),
            Div(style="width: 80px;"),
            style="display: grid; grid-template-columns: auto 1fr auto; align-items: center; margin-top: 1rem; margin-bottom: 2rem;"
        ),
        Form(
            Fieldset(
                Div(
                    Label(
                        Input(
                            type="radio",
                            name="tipo_operacao",
                            value="compra"
                        ),
                        " Compra",
                        style="margin-right: 20px; cursor: pointer;"
                    ),
                    Label(
                        Input(
                            type="radio",
                            name="tipo_operacao",
                            value="venda",
                            checked=True  # Mantém 'Venda' como padrão
                        ),
                        " Venda",
                        style="margin-right: 20px; cursor: pointer;"
                    ),
                    Label(
                        Input(
                            type="radio",
                            name="tipo_operacao",
                            value="estoque"
                        ),
                        " Estoque",
                        style="cursor: pointer;"
                    ),
                    style="margin-bottom: 1rem; display: flex; align-items: center;"
                ),
                Input(
                    id="campo-pergunta",
                    name="nome", 
                    placeholder="Digite sua pergunta...", 
                    required=True, 
                    autofocus=True 
                ),
                Button("Enviar", type="submit"),
                
                # --- BOTÕES DE PESQUISA ALINHADOS COM O BOTÃO ENVIAR ---
                Div(
                    Button(
                        "🔍 Pesquisar Produto", 
                        type="button",
                        cls="secondary outline",
                        style="flex: 1; padding: 0.5rem 0.2rem; font-size: 0.85rem; margin: 0;",
                        hx_get="/modal-pesquisa",
                        hx_target="#container-modal",
                        hx_swap="innerHTML"
                    ),
                    Button(
                        "🔍 Pesquisar Cliente", 
                        type="button",
                        cls="secondary outline",
                        style="flex: 1; padding: 0.5rem 0.2rem; font-size: 0.85rem; margin: 0;",
                        hx_get="/modal-pesquisa-cliente",
                        hx_target="#container-modal",
                        hx_swap="innerHTML"
                    ),
                    Button(
                        "🔍 Pesquisar Vendedor", 
                        type="button",
                        cls="secondary outline",
                        style="flex: 1; padding: 0.5rem 0.2rem; font-size: 0.85rem; margin: 0;",
                        hx_get="/modal-pesquisa-vendedor",
                        hx_target="#container-modal",
                        hx_swap="innerHTML"
                    ),
                    Button(
                        "🔍 Pesquisar Posicionamento", 
                        type="button",
                        cls="secondary outline",
                        style="flex: 1; padding: 0.5rem 0.2rem; font-size: 0.85rem; margin: 0;",
                        hx_get="/modal-pesquisa-posicionamento",
                        hx_target="#container-modal",
                        hx_swap="innerHTML"
                    ),
                    Button(
                        "🔍 Pesquisar Grupo", 
                        type="button",
                        cls="secondary outline",
                        style="flex: 1; padding: 0.5rem 0.2rem; font-size: 0.85rem; margin: 0;",
                        hx_get="/modal-pesquisa-grupo",
                        hx_target="#container-modal",
                        hx_swap="innerHTML"
                    ),
                    style="display: flex; gap: 8px; width: 100%; margin-top: 0.5rem;"
                )
            ),
            hx_post="/resultado",
            hx_target="#resultado",
            hx_swap="innerHTML",
            hx_indicator="body"
        ),
                
        Div(id="resultado"),
        Div(id="container-modal"),
        cls="container"
    )

# ============================================================
# ROTAS DO MODAL DE PESQUISA DE CLIENTES
# ============================================================

@router("/modal-pesquisa-cliente")
def modal_pesquisa_cliente():
    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 = ""):
    clientes = buscar_cliente(busca)
    return render_tabela_cl1(clientes, busca)

@router("/selecionar-cliente")
def selecionar_cliente(codigo: str):
    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():
    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 = ""):
    vendedores = buscar_vendedor(busca)
    return render_tabela_vd1(vendedores, busca)

@router("/selecionar-vendedor")
def selecionar_vendedor(codigo: str):
    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 PRODUTOS
# ============================================================

@router("/modal-pesquisa")
def modal_pesquisa():
    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):
    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 POSICIONAMENTO
# ============================================================

@router("/modal-pesquisa-posicionamento")
def modal_pesquisa_posicionamento():
    posicionamentos = buscar_posic("")
    return Div(
        Div(
            Header(
                Div(
                    Img(src="/logoia.jpg", width="80", cls="img-fluid", style="height: auto; border-radius: 10px;"),
                    H3("Pesquisa de Posicionamento", 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 a descrição do posicionamento...",
                    hx_post="/buscar-posicionamento-modal", hx_target="#tabela-modal-posicionamento", hx_trigger="input changed delay:300ms"
                )
            ),
            Div(id="tabela-modal-posicionamento", children=render_tabela_po1(posicionamentos, "")),
            cls="modal-content"
        ),
        cls="modal-overlay"
    )

@router("/buscar-posicionamento-modal", methods=["POST"])
def buscar_posicionamento_modal(busca: str = ""):
    posicionamentos = buscar_posic(busca)
    return render_tabela_po1(posicionamentos, busca)

@router("/selecionar-posic")
def selecionar_posic(codigo: str):
    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 GRUPO
# ============================================================

@router("/modal-pesquisa-grupo")
def modal_pesquisa_grupo():
    grupos = buscar_grupo("")
    return Div(
        Div(
            Header(
                Div(
                    Img(src="/logoia.jpg", width="80", cls="img-fluid", style="height: auto; border-radius: 10px;"),
                    H3("Pesquisa de Grupos", 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 a descrição do grupo...",
                    hx_post="/buscar-grupo-modal", hx_target="#tabela-modal-grupo", hx_trigger="input changed delay:300ms"
                )
            ),
            Div(id="tabela-modal-grupo", children=render_tabela_gru(grupos, "")),
            cls="modal-content"
        ),
        cls="modal-overlay"
    )

@router("/buscar-grupo-modal", methods=["POST"])
def buscar_grupo_modal(busca: str = ""):
    grupos = buscar_grupo(busca)
    return render_tabela_gru(grupos, busca)

@router("/selecionar-grupo")
def selecionar_grupo(codigo: str):
    return Script(f"""
        document.getElementById('campo-pergunta').value += ' {codigo} ';
        document.getElementById('container-modal').innerHTML = '';
        document.getElementById('campo-pergunta').focus();
    """)

# ============================================================
# ROTAS DE PROCESSAMENTO E IA
# ============================================================

@router("/resultado", methods=["POST"])
def resultado_post(nome: str, tipo_operacao: str = "venda"):
    try:
        processo = subprocess.run(
            [sys.executable, "grok.py", nome, tipo_operacao],
            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("Pergunta fora do contexto!", style="color: #dc3545; margin-top: 20px;"),
#            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()