import re
import sys
import os
import subprocess
import psycopg2
from psycopg2.extras import RealDictCursor
from fasthtml.common import *
from starlette.responses import FileResponse

# Configuração do Banco de Dados PostgreSQL
DB_CONFIG = {
    "dbname": "bdps01",
    "user": "postgres",
    "password": "ps@web",
    "host": "127.0.0.1",
    "port": 5432,
}

# --- FUNÇÕES DE BANCO DE DADOS (CLIENTES & PRODUTOS) ---

def buscar_cliente(termo: str = ""):
    """Consulta os clientes na tabela clienteia do PostgreSQL."""
    termo_limpo = termo.strip()
    try:
        conn = psycopg2.connect(**DB_CONFIG)
        conn.set_client_encoding('WIN1252')
        cursor = conn.cursor(cursor_factory=RealDictCursor)

        query = """
            SELECT cl1codig AS "Codigo", cl1nomec AS "Nome", cl1cnpj AS "CNPJ / CPF" 
            FROM clienteia
            WHERE cl1nomec ILIKE %s
            ORDER BY cl1nomec 
            LIMIT 50;
        """
        parametro = (f"%{termo_limpo}%",)

        try:
            query_bytes = cursor.mogrify(query, parametro)
            print("\n--- QUERY CLIENTE EXECUTADA ---")
            print(query_bytes.decode('utf-8', errors='replace'))
            print("-------------------------------\n")
        except Exception as err_print:
            print(f"Aviso: Não foi possível imprimir a query: {err_print}")

        cursor.execute(query, parametro)
        clientes = cursor.fetchall()

        cursor.close()
        conn.close()
        return clientes
    except Exception as e:
        print(f"Erro na consulta SQL de Clientes: {e}")
        return []

def buscar_produto(termo: str = ""):
    """Consulta os produtos na tabela produtoia do PostgreSQL ou fallback."""
    termo_limpo = termo.strip()
    try:
        conn = psycopg2.connect(**DB_CONFIG)
        conn.set_client_encoding('WIN1252')
        cursor = conn.cursor(cursor_factory=RealDictCursor)

        query = """
            SELECT pr1codig AS "Codigo", pr1nomec AS "Nome"
            FROM produtoia
            WHERE pr1nomec ILIKE %s
            ORDER BY pr1nomec 
            LIMIT 50;
        """
        parametro = (f"%{termo_limpo}%",)
        cursor.execute(query, parametro)
        produtos = cursor.fetchall()

        cursor.close()
        conn.close()
        return produtos
    except Exception as e:
        print(f"Aviso/Erro na consulta de Produtos: {e}")
        # Retorno de fallback caso a tabela de produtos ainda não esteja configurada
        return [
            {"Codigo": "PROD01", "Nome": "Produto Exemplo A"},
            {"Codigo": "PROD02", "Nome": "Produto Exemplo B"}
        ]

# --- FUNÇÕES DE FORMATAÇÃO E TABELAS ---

def destacar_termo(texto: str, termo: str) -> str:
    """Destaca o termo buscado nas tabelas."""
    termo_limpo = termo.strip()
    if not termo_limpo or not texto:
        return str(texto)
    padrao = re.compile(f"({re.escape(termo_limpo)})", re.IGNORECASE)
    return padrao.sub(r"<strong>\1</strong>", str(texto))

def render_tabela_geral(dados, termo: str = "", tipo: str = "cliente"):
    """Gera a tabela HTML padronizada para clientes ou produtos."""
    if not dados:
        msg = "Nenhum cliente encontrado." if tipo == "cliente" else "Nenhum produto encontrado."
        return P(msg, style="color: gray; padding: 10px;")

    colunas = list(dados[0].keys())
    header = Tr(*[Th(col.replace("_", " ").title()) for col in colunas])

    linhas = []
    for item in dados:
        celulas = []
        for col in colunas:
            valor_original = str(item[col] if item[col] is not None else "")
            valor_formatado = destacar_termo(valor_original, termo)

            if col == "Codigo":
                # Botão com imagem
                botao_seleciona = A(
                    Button(
                        Img(
                            src=f"/static/{valor_original}.jpg",
                            alt=f"Código {valor_original}",
                            width="40",
                            height="40",
                            style="width: 40px; height: 40px; object-fit: cover; vertical-align: middle; border-radius: 6px;",
                            onerror="this.onerror=null; this.src='/logoia.jpg';",
                        ),
                        cls="outline",
                        style="margin-right: 10px; padding: 2px 8px; font-size: 0.85rem;",
                    ),
                    hx_get=f"/selecionar-codigo?codigo={valor_original}",
                    hx_target="#container-modal",
                )
                celulas.append(Td(botao_seleciona, NotStr(valor_formatado)))
            else:
                celulas.append(Td(NotStr(valor_formatado)))

        linhas.append(Tr(*celulas))

    return Div(
        Table(
            Thead(header),
            Tbody(*linhas),
            cls="striped tabela-com-moldura",
        ),
        cls="tabela-container",
    )

# --- CONFIGURAÇÃO DA APLICAÇÃO E CSS GLOBAL ---

css_personalizado = Style("""
body.htmx-request, body.htmx-request * {
    cursor: wait !important;
}
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;
}
.tabela-container {
    border: 2px solid #0D6EFD !important;
    border-radius: 12px !important;
    overflow: hidden !important;
}
.tabela-com-moldura {
    width: 100% !important;
    border-collapse: separate !important;
    border-spacing: 0 !important;
    margin: 0 !important;
}
.tabela-com-moldura th:not(:last-child),
.tabela-com-moldura td:not(:last-child) {
    border-right: 1px solid #ccc !important;
}
.tabela-com-moldura th, 
.tabela-com-moldura td {
    border-bottom: 1px solid #eee !important;
}
.tabela-com-moldura tr:last-child td {
    border-bottom: none !important;
}
.tabela-com-moldura th {
    color: #0D6EFD !important;
    font-weight: bold !important;
}
.tab-btn-active {
    background-color: #0D6EFD !important;
    color: white !important;
}
""")

app, router = fast_app(file_path=".", hdrs=(css_personalizado,))

# --- ROTAS PRINCIPAIS ---

@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(
                Input(
                    id="campo-pergunta",
                    name="nome", 
                    placeholder="Digite sua pergunta...", 
                    required=True, 
                    autofocus=True 
                ),
                Button("Enviar", type="submit"),
                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"
                )
            ),
            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 (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;"
                    ),
                    Div(
                        Button("📦 Produtos", cls="tab-btn-active", hx_get="/modal-pesquisa", hx_target="#container-modal"),
                        Button("👤 Clientes", cls="outline", hx_get="/modal-pesquisa-cliente", hx_target="#container-modal"),
                        style="display: flex; gap: 10px;"
                    ),
                    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_geral(produtos, "", tipo="produto")),
            cls="modal-content"
        ),
        cls="modal-overlay"
    )

@router("/buscar-produto-modal", methods=["POST"])
def buscar_modal(busca: str = ""):
    produtos = buscar_produto(busca)
    return render_tabela_geral(produtos, busca, tipo="produto")

# --- ROTAS DO MODAL DE PESQUISA (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;"
                    ),
                    Div(
                        Button("📦 Produtos", cls="outline", hx_get="/modal-pesquisa", hx_target="#container-modal"),
                        Button("👤 Clientes", cls="tab-btn-active", hx_get="/modal-pesquisa-cliente", hx_target="#container-modal"),
                        style="display: flex; gap: 10px;"
                    ),
                    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_geral(clientes, "", tipo="cliente")),
            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_geral(clientes, busca, tipo="cliente")

@router("/selecionar-codigo")
def selecionar_codigo(codigo: str):
    """Insere o código do item selecionado e fecha o modal."""
    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):
    try:
        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()
