"""
Atualizador automático do Dashboard - Tião Silva
Lê o arquivo Excel e regenera os dados embutidos no dashboard.html
"""

import openpyxl
import json
import re
import os
import sys
import glob
import webbrowser
from datetime import datetime

# ──────────────────────────────────────────────────────────────
# CONFIGURAÇÕES
# Edite EXCEL_PATH se o arquivo estiver em outro local.
# Deixe EXCEL_PATH = "" para busca automática.
# ──────────────────────────────────────────────────────────────
EXCEL_PATH = ""   # ← preencha aqui o caminho completo se necessário

# Locais de busca automática (se EXCEL_PATH estiver vazio)
LOCAIS_BUSCA = [
    r"D:\Users\Claudio\Desktop",
    r"D:\Users\Claudio\OneDrive",
    r"D:\Users\Claudio\Documents",
    r"C:\Users\Claudio\Desktop",
    r"C:\Users\Claudio\OneDrive",
    r"C:\Users\Claudio\Documents",
    os.path.dirname(os.path.abspath(__file__)),
]
PALAVRAS_CHAVE_ARQUIVO = ["evolu", "categoria", "tiao", "silva"]

DASHBOARD_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dashboard.html")

ANOS_ABAS = {
    2017: "Evolução Jan a dez-17",
    2018: "Evolução jan a dez-18",
    2019: "Evolução jan a dez-19",
    2020: "Evolução jan a dez-20",
    2021: "Evolução jan a dez-21",
    2022: "Evolução jan a dez-22",
    2023: "Evolução jan a dez-23",
    2024: "Evolução jan a dez-24",
    2025: "Evolução jan a dez-25",
}

MESES_NOMES = [
    "JANEIRO", "FEVEREIRO", "MARÇO", "ABRIL", "MAIO", "JUNHO",
    "JULHO",   "AGOSTO",   "SETEMBRO", "OUTUBRO", "NOVEMBRO", "DEZEMBRO",
]

# ──────────────────────────────────────────────────────────────
# LOCALIZAR ARQUIVO EXCEL
# ──────────────────────────────────────────────────────────────

def localizar_excel():
    # 1. Caminho fixo configurado
    if EXCEL_PATH and os.path.exists(EXCEL_PATH):
        return EXCEL_PATH

    # 2. Arquivo salvo da última execução
    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "excel_path.txt")
    if os.path.exists(config_path):
        with open(config_path, encoding="utf-8") as f:
            saved = f.read().strip()
        if saved and os.path.exists(saved):
            log(f"  Usando caminho salvo: {saved}")
            return saved

    # 3. Busca automática por palavra-chave
    log("  Buscando arquivo Excel automaticamente...")
    candidatos = []
    for pasta in LOCAIS_BUSCA:
        if not os.path.isdir(pasta):
            continue
        for arq in os.listdir(pasta):
            if not arq.lower().endswith(".xlsx"):
                continue
            nome_lower = arq.lower()
            if all(p in nome_lower for p in PALAVRAS_CHAVE_ARQUIVO[:2]):   # "evolu" e "categoria"
                candidatos.append(os.path.join(pasta, arq))

    if len(candidatos) == 1:
        caminho = candidatos[0]
        # Salvar para próximas execuções
        with open(config_path, "w", encoding="utf-8") as f:
            f.write(caminho)
        log(f"  Arquivo encontrado: {os.path.basename(caminho)}")
        return caminho

    if len(candidatos) > 1:
        print("\n  Múltiplos arquivos encontrados:")
        for i, c in enumerate(candidatos, 1):
            print(f"    [{i}] {c}")
        try:
            escolha = int(input("\n  Escolha o número do arquivo: ").strip())
            caminho = candidatos[escolha - 1]
            with open(config_path, "w", encoding="utf-8") as f:
                f.write(caminho)
            return caminho
        except (ValueError, IndexError):
            pass

    return None


# ──────────────────────────────────────────────────────────────
# EXTRAÇÃO DOS DADOS DO EXCEL
# ──────────────────────────────────────────────────────────────

def extrair_dados(excel_path):
    log(f"Lendo: {excel_path}")
    wb = openpyxl.load_workbook(excel_path, data_only=True)
    dados, fat_total = {}, {}

    for ano, aba in ANOS_ABAS.items():
        if aba not in wb.sheetnames:
            log(f"  [!] Aba '{aba}' não encontrada — ignorando {ano}.")
            continue

        ws = wb[aba]
        all_rows = list(ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True))

        # Localizar linha de cabeçalho (contém "JANEIRO")
        header_row = None
        for ri, row in enumerate(all_rows):
            if any(isinstance(c, str) and c.strip().upper() == "JANEIRO" for c in row):
                header_row = ri
                break

        if header_row is None:
            log(f"  [!] Cabeçalho de meses não localizado em {ano}.")
            continue

        # Mapear mês → índice de coluna (0-based)
        mes_cols = {}
        for ri_offset in range(2):
            ri = header_row + ri_offset
            if ri >= len(all_rows):
                break
            for ci, cell in enumerate(all_rows[ri]):
                if isinstance(cell, str):
                    m = cell.strip().upper()
                    if m in MESES_NOMES and m not in mes_cols:
                        mes_cols[m] = ci

        col_list = [mes_cols.get(m) for m in MESES_NOMES]

        # Ler linhas de dados
        dados[ano], fat_total[ano] = {}, [None] * 12

        for row in all_rows[header_row + 1:]:
            cat = row[1] if len(row) > 1 else None
            if not cat or not isinstance(cat, str):
                continue
            cat = cat.strip()
            if not cat:
                continue

            vendas = []
            for ci in col_list:
                v = (row[ci] if ci is not None and ci < len(row) else None)
                vendas.append(round(float(v), 2) if isinstance(v, (int, float)) and v > 1000 else None)

            if "FATURAMENTO TOTAL" in cat.upper():
                fat_total[ano] = vendas
            elif any(v for v in vendas if v):
                dados[ano][cat] = vendas

        ok_meses = sum(1 for v in fat_total[ano] if v)
        log(f"  [OK] {ano} — {len(dados[ano])} categorias, {ok_meses}/12 meses com dados")

    wb.close()
    return dados, fat_total


# ──────────────────────────────────────────────────────────────
# ATUALIZAÇÃO DO dashboard.html
# ──────────────────────────────────────────────────────────────

def atualizar_html(dados, fat_total, excel_path):
    log(f"Atualizando: {DASHBOARD_PATH}")
    if not os.path.exists(DASHBOARD_PATH):
        raise FileNotFoundError(f"dashboard.html não encontrado:\n  {DASHBOARD_PATH}")

    with open(DASHBOARD_PATH, encoding="utf-8") as f:
        html = f.read()

    # 1. Substituir bloco de dados
    novo_raw = json.dumps(
        {"dados":     {str(k): v for k, v in dados.items()},
         "fat_total": {str(k): v for k, v in fat_total.items()}},
        ensure_ascii=False,
        separators=(",", ":"),
    )
    novo_const = f"const RAW = {novo_raw};"
    html_novo, n = re.subn(r"const RAW = \{.*?\};", novo_const, html, flags=re.DOTALL)
    if n == 0:
        log("  [!] Padrão 'const RAW = {...};' não encontrado no HTML.")
        return False
    log(f"  Dados embutidos — {len(novo_raw):,} bytes de JSON")

    # 2. Atualizar timestamp no comentário JS
    agora = datetime.now().strftime("%d/%m/%Y %H:%M")
    html_novo = re.sub(
        r"// RAW DATA.*?ULTIMA_ATUALIZACAO:.*?\n",
        f"// RAW DATA  |  ULTIMA_ATUALIZACAO: {agora}\n",
        html_novo,
    )

    # 3. Atualizar o <span id="tsUpdate"> no HTML
    html_novo = re.sub(
        r'(<span id="tsUpdate">).*?(</span>)',
        rf'\g<1>{agora}\2',
        html_novo,
    )

    # 4. Atualizar o nome do arquivo no rodapé (se existir)
    nome_arq = os.path.basename(excel_path)
    html_novo = re.sub(
        r'(<span id="srcFile">).*?(</span>)',
        rf'\g<1>{nome_arq}\2',
        html_novo,
    )

    with open(DASHBOARD_PATH, "w", encoding="utf-8") as f:
        f.write(html_novo)

    log(f"  [OK] Dashboard salvo — {len(html_novo):,} bytes")
    return True


# ──────────────────────────────────────────────────────────────
# UTILIDADES
# ──────────────────────────────────────────────────────────────

def log(msg):
    print(f"[{datetime.now():%H:%M:%S}] {msg}")


# ──────────────────────────────────────────────────────────────
# MAIN
# ──────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print()
    print("=" * 55)
    print("  Dashboard Tião Silva — Atualizador de Dados")
    print("=" * 55)
    print()
    try:
        excel_path = localizar_excel()

        if not excel_path:
            print("\n  [ERRO] Arquivo Excel não encontrado!")
            print("  Informe o caminho completo do arquivo .xlsx:")
            excel_path = input("  > ").strip().strip('"')
            if not os.path.exists(excel_path):
                print(f"\n  [ERRO] Arquivo não encontrado: {excel_path}\n")
                sys.exit(1)
            # Salvar para próximas execuções
            config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "excel_path.txt")
            with open(config_path, "w", encoding="utf-8") as f:
                f.write(excel_path)

        dados, fat_total = extrair_dados(excel_path)
        ok = atualizar_html(dados, fat_total, excel_path)

        if ok and "--no-browser" not in sys.argv:
            log("Abrindo dashboard no navegador...")
            webbrowser.open(f"file:///{DASHBOARD_PATH.replace(os.sep, '/')}")

        print()
        print("  Concluido com sucesso!")
        print()

    except FileNotFoundError as e:
        print(f"\n  [ERRO] {e}\n")
        input("  Pressione Enter para fechar...")
        sys.exit(1)
    except Exception as e:
        import traceback
        print(f"\n  [ERRO INESPERADO] {e}")
        traceback.print_exc()
        input("\n  Pressione Enter para fechar...")
        sys.exit(1)
