with open('dashboard_estoque.html','r',encoding='utf-8') as f:
    html = f.read()

OLD_JS_START = '// ════════════════════════════════════════════\n//  IA — ANÁLISE DE FORNECEDOR (ChatGPT + Gemini)\n// ════════════════════════════════════════════'
idx_start = html.find(OLD_JS_START)
idx_end   = html.find('\n</script>', idx_start)
if idx_start < 0:
    print("ERRO: bloco JS nao encontrado")
    exit()

NEW_JS = r"""
// ════════════════════════════════════════════
//  IA CHAT — ANÁLISE DE FORNECEDOR
// ════════════════════════════════════════════
let _iaFornNome  = '';
let _iaProds     = [];
let _iaProvider  = 'groq';
let _iaChatHistory = [];   // histórico de mensagens {role, content}

// ── Config por provider ──────────────────────
const IA_CFG = {
  chatgpt: { cor:'#10a37f', bg:'#f0fdf9', txt:'#065f46', label:'Chave API OpenAI',        ph:'sk-...',  btnBg:'linear-gradient(135deg,#10a37f,#0d8c6d)', link:'https://platform.openai.com/api-keys',   linkTxt:'platform.openai.com',   free:false },
  gemini:  { cor:'#4285f4', bg:'#eff6ff', txt:'#1d4ed8', label:'Chave API Google Gemini', ph:'AIza...', btnBg:'linear-gradient(135deg,#4285f4,#1a73e8)', link:'https://aistudio.google.com/app/apikey', linkTxt:'aistudio.google.com',   free:true  },
  groq:    { cor:'#f97316', bg:'#fff7ed', txt:'#c2410c', label:'Chave API Groq (Grátis)', ph:'gsk_...', btnBg:'linear-gradient(135deg,#f97316,#ea580c)', link:'https://console.groq.com/keys',          linkTxt:'console.groq.com',      free:true  },
};

function selectIa(provider) {
  _iaProvider = provider;
  const c = IA_CFG[provider];
  ['chatgpt','gemini','groq'].forEach(p => {
    const btn = document.getElementById('btnIa' + p.charAt(0).toUpperCase() + p.slice(1));
    if (!btn) return;
    const pc = IA_CFG[p]; const active = p === provider;
    btn.style.cssText = `flex:1;min-width:80px;padding:8px;border-radius:8px;border:2px solid ${active?pc.cor:'transparent'};background:${active?pc.bg:'#f8fafc'};color:${active?pc.txt:'#64748b'};font-weight:700;font-size:12px;cursor:pointer;transition:all .2s`;
  });
  document.getElementById('iaApiLabel').textContent = c.label;
  document.getElementById('iaApiKey').placeholder   = c.ph;
  document.getElementById('iaBtnAnalise').style.background = c.btnBg;
  const linkEl = document.getElementById('iaApiLinkHref');
  linkEl.href = c.link; linkEl.textContent = c.linkTxt;
  const nota = document.getElementById('iaApiLink');
  nota.innerHTML = c.free
    ? `⚡ <strong>${provider==='groq'?'Groq':'Gemini'} é gratuito</strong>. Crie sua chave em <a href="${c.link}" target="_blank" style="color:${c.cor}" id="iaApiLinkHref">${c.linkTxt}</a>`
    : `Sua chave fica salva apenas neste navegador. Obtenha em <a href="${c.link}" target="_blank" style="color:${c.cor}" id="iaApiLinkHref">${c.linkTxt}</a>`;
  const saved = localStorage.getItem('ia_key_' + provider) || '';
  document.getElementById('iaApiKey').value = saved;
}

function saveIaKey() {
  localStorage.setItem('ia_key_' + _iaProvider, document.getElementById('iaApiKey').value);
}

// ── Abrir modal ───────────────────────────────
function openIaModal() {
  document.getElementById('iaModal').style.display = 'flex';
  document.getElementById('iaOverlay').style.display = 'block';
  _iaFornNome = document.getElementById('drawerTitle').childNodes[0].textContent.trim();
  document.getElementById('iaNomeForn').textContent = _iaFornNome;
  _iaProds = window._drawerProds || [];
  _iaChatHistory = [];
  selectIa(_iaProvider);
  document.getElementById('iaChatMsgs').innerHTML = `
    <div style="text-align:center;padding:40px 20px;color:#94a3b8">
      <div style="font-size:48px;margin-bottom:12px">🤖</div>
      <div style="font-size:14px;line-height:1.7">Configure sua chave API e clique em <strong>Analisar Agora</strong>.<br>Depois você pode fazer perguntas sobre este fornecedor.</div>
    </div>`;
  document.getElementById('iaChatInput').value = '';
}

function closeIaModal() {
  document.getElementById('iaModal').style.display = 'none';
  document.getElementById('iaOverlay').style.display = 'none';
}

// ── Prompt inicial detalhado ──────────────────
function buildSystemPrompt() {
  return `Você é um consultor sênior especializado em gestão de estoque, compras e estratégia comercial para lojas de material de construção no Brasil.

Seu papel é analisar dados de estoque parado, identificar riscos financeiros, sugerir ações práticas de vendas, promoções e negociações com fornecedores.

Sempre responda em português brasileiro, de forma objetiva, estruturada e acionável. Use emojis para facilitar a leitura. Quando não tiver dados suficientes para uma resposta, indique o que seria necessário para uma análise mais precisa.`;
}

function buildAnalysisPrompt() {
  const top30 = _iaProds.slice(0, 30);
  const vlrTotal   = _iaProds.reduce((s,p) => s+(p.vl_est||0), 0);
  const qtdTotal   = _iaProds.length;
  const topVlr     = [..._iaProds].sort((a,b)=>(b.vl_est||0)-(a.vl_est||0)).slice(0,5);
  const maisAntigos= [..._iaProds].filter(p=>p.dias).sort((a,b)=>b.dias-a.dias).slice(0,5);

  const listaTop = top30.map((p,i) =>
    `${i+1}. ${p.nome} | Estoque: ${p.estoque} un | Custo unit: R$ ${(p.custo||0).toFixed(2)} | Valor parado: R$ ${(p.vl_est||0).toFixed(2)}${p.dias?' | '+p.dias+' dias sem entrada':''}`
  ).join('\n');

  const topVlrStr = topVlr.map(p=>`• ${p.nome}: R$ ${(p.vl_est||0).toLocaleString('pt-BR',{minimumFractionDigits:2})}`).join('\n');
  const maisAntigosStr = maisAntigos.map(p=>`• ${p.nome}: ${p.dias} dias parado`).join('\n');

  return `ANÁLISE COMPLETA DE ESTOQUE PARADO

FORNECEDOR: ${_iaFornNome}
Total de produtos parados: ${qtdTotal} itens
Valor total imobilizado: R$ ${vlrTotal.toLocaleString('pt-BR',{minimumFractionDigits:2})}

TOP 5 MAIOR VALOR PARADO:
${topVlrStr}

TOP 5 MAIS ANTIGOS SEM MOVIMENTAÇÃO:
${maisAntigosStr}

LISTA COMPLETA (top ${top30.length}):
${listaTop}

Por favor, faça uma análise completa respondendo TODOS os tópicos abaixo:

## 📊 1. DIAGNÓSTICO GERAL
Avalie a gravidade da situação, o capital em risco e o impacto no fluxo de caixa.

## 🔍 2. PRODUTOS CRÍTICOS
Identifique os produtos com maior risco (alto valor + muito tempo parado) e explique por quê são prioritários.

## 🛍️ 3. ESTRATÉGIAS DE PROMOÇÃO E VENDAS
Sugira pelo menos 5 ações concretas para movimentar esses produtos (combos, descontos progressivos, liquidação, kits, etc).

## 🤝 4. NEGOCIAÇÃO COM O FORNECEDOR
Como negociar com este fornecedor? (devolução, troca, bonificação, crédito, desconto na próxima compra)

## 🛒 5. RECOMENDAÇÃO DE COMPRA
O que NÃO comprar mais? O que comprar com cautela? Quais critérios usar na próxima negociação?

## 📅 6. PLANO DE AÇÃO (30/60/90 dias)
Monte um plano de ação em 3 fases com ações específicas para cada período.

## 🎯 7. AÇÕES IMEDIATAS (esta semana)
Liste as 3 ações mais urgentes para tomar agora.`;
}

// ── Renderizar mensagem no chat ───────────────
function addChatMsg(role, content, model) {
  const msgs = document.getElementById('iaChatMsgs');
  const c = IA_CFG[_iaProvider];
  const isUser = role === 'user';

  const rendered = content
    .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
    .replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>')
    .replace(/^## (.+)$/gm,'<h3 style="color:#1e293b;margin:16px 0 8px;font-size:15px;border-bottom:2px solid #e2e8f0;padding-bottom:6px">$1</h3>')
    .replace(/^### (.+)$/gm,'<h4 style="color:#334155;margin:12px 0 6px;font-size:14px">$1</h4>')
    .replace(/^- (.+)$/gm,'<li style="margin:4px 0;color:#374151">$1</li>')
    .replace(/^(\d+)\. (.+)$/gm,'<li style="margin:5px 0;color:#374151"><strong>$1.</strong> $2</li>')
    .replace(/(<li[^>]*>[\s\S]*?<\/li>)/g, m => '<ul style="margin:8px 0 10px 18px">'+m+'</ul>')
    .replace(/\n\n/g,'</p><p style="margin:8px 0;color:#374151;line-height:1.75">')
    .replace(/\n/g,'<br>');

  const div = document.createElement('div');
  div.style.cssText = `display:flex;flex-direction:${isUser?'row-reverse':'row'};gap:10px;align-items:flex-start`;
  div.innerHTML = `
    <div style="width:34px;height:34px;border-radius:10px;background:${isUser?'#6366f1':c.cor};display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0">
      ${isUser?'👤':'🤖'}
    </div>
    <div style="max-width:82%;background:${isUser?'linear-gradient(135deg,#6366f1,#4f46e5)':'#fff'};color:${isUser?'#fff':'#374151'};border-radius:${isUser?'14px 4px 14px 14px':'4px 14px 14px 14px'};padding:14px 16px;font-size:13.5px;line-height:1.75;box-shadow:0 2px 8px rgba(0,0,0,.08)">
      <p style="margin:0;color:${isUser?'#fff':'#374151'};line-height:1.75">${rendered}</p>
      ${model?`<div style="margin-top:10px;font-size:11px;color:${isUser?'rgba(255,255,255,.6)':'#94a3b8'}">${model} · ${new Date().toLocaleTimeString('pt-BR')}</div>`:''}
    </div>`;
  msgs.appendChild(div);
  msgs.parentElement.scrollTop = msgs.parentElement.scrollHeight;
}

function addThinking() {
  const msgs = document.getElementById('iaChatMsgs');
  const c = IA_CFG[_iaProvider];
  const div = document.createElement('div');
  div.id = 'iaThinking';
  div.style.cssText = 'display:flex;gap:10px;align-items:flex-start';
  div.innerHTML = `
    <div style="width:34px;height:34px;border-radius:10px;background:${c.cor};display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0">🤖</div>
    <div style="background:#fff;border-radius:4px 14px 14px 14px;padding:14px 20px;box-shadow:0 2px 8px rgba(0,0,0,.08);display:flex;gap:6px;align-items:center">
      <span style="width:8px;height:8px;background:${c.cor};border-radius:50%;animation:bounce .8s infinite"></span>
      <span style="width:8px;height:8px;background:${c.cor};border-radius:50%;animation:bounce .8s .15s infinite"></span>
      <span style="width:8px;height:8px;background:${c.cor};border-radius:50%;animation:bounce .8s .3s infinite"></span>
    </div>`;
  msgs.appendChild(div);
  msgs.parentElement.scrollTop = msgs.parentElement.scrollHeight;
}

function removeThinking() {
  const t = document.getElementById('iaThinking');
  if (t) t.remove();
}

// ── Chamar API ────────────────────────────────
async function callIaApi(messages) {
  const key = (document.getElementById('iaApiKey').value||'').trim();
  if (!key) throw new Error('Chave API não configurada');
  localStorage.setItem('ia_key_' + _iaProvider, key);

  if (_iaProvider === 'groq') {
    const resp = await fetch('https://api.groq.com/openai/v1/chat/completions', {
      method:'POST',
      headers:{'Content-Type':'application/json','Authorization':'Bearer '+key},
      body: JSON.stringify({ model:'llama-3.3-70b-versatile', messages, max_tokens:2000, temperature:0.7 })
    });
    if (!resp.ok) { const e=await resp.json(); throw new Error(e.error?.message||'Erro Groq'); }
    const d = await resp.json();
    return { text: d.choices[0].message.content, model:'Groq · LLaMA 3.3 70B' };

  } else if (_iaProvider === 'chatgpt') {
    const resp = await fetch('https://api.openai.com/v1/chat/completions', {
      method:'POST',
      headers:{'Content-Type':'application/json','Authorization':'Bearer '+key},
      body: JSON.stringify({ model:'gpt-4o-mini', messages, max_tokens:2000, temperature:0.7 })
    });
    if (!resp.ok) { const e=await resp.json(); throw new Error(e.error?.message||'Erro OpenAI'); }
    const d = await resp.json();
    return { text: d.choices[0].message.content, model:'ChatGPT · GPT-4o Mini' };

  } else {
    // Gemini — não suporta histórico diretamente, usa último user msg
    const lastUser = messages.filter(m=>m.role==='user').pop();
    const models = ['gemini-1.5-flash-latest','gemini-1.5-flash','gemini-pro'];
    for (const model of models) {
      const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${key}`;
      const resp = await fetch(url, {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ contents:[{ parts:[{ text: lastUser.content }] }] })
      });
      if (resp.ok) {
        const d = await resp.json();
        return { text: d.candidates[0].content.parts[0].text, model:'Gemini · '+model };
      }
    }
    throw new Error('Cota Gemini esgotada. Use Groq (grátis) ou ChatGPT.');
  }
}

// ── Análise inicial ───────────────────────────
async function runIaAnalysis() {
  const key = (document.getElementById('iaApiKey').value||'').trim();
  if (!key) {
    document.getElementById('iaChatMsgs').innerHTML = `
      <div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:12px;padding:16px;color:#dc2626;font-size:14px;margin:10px">
        ⚠️ Insira sua chave API e clique em <strong>Analisar Agora</strong>. Groq é gratuito em <a href="https://console.groq.com/keys" target="_blank">console.groq.com</a>
      </div>`;
    return;
  }

  _iaChatHistory = [];
  document.getElementById('iaChatMsgs').innerHTML = '';
  document.getElementById('iaBtnAnalise').disabled = true;
  document.getElementById('iaBtnAnalise').textContent = '⏳ Analisando...';

  const sysMsg   = { role:'system',    content: buildSystemPrompt() };
  const userMsg  = { role:'user',      content: buildAnalysisPrompt() };
  _iaChatHistory = [sysMsg, userMsg];

  addChatMsg('user', `📋 Análise completa do fornecedor **${_iaFornNome}** — ${_iaProds.length} produtos parados`);
  addThinking();

  try {
    const r = await callIaApi(_iaChatHistory);
    removeThinking();
    _iaChatHistory.push({ role:'assistant', content: r.text });
    addChatMsg('assistant', r.text, r.model);
  } catch(e) {
    removeThinking();
    document.getElementById('iaChatMsgs').innerHTML += `
      <div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:12px;padding:14px;color:#dc2626;font-size:13px;margin:6px 0">
        <strong>Erro:</strong> ${e.message}
      </div>`;
  } finally {
    document.getElementById('iaBtnAnalise').disabled = false;
    document.getElementById('iaBtnAnalise').textContent = '🚀 Analisar Agora';
  }
}

// ── Enviar mensagem no chat ───────────────────
async function sendIaChat() {
  const input = document.getElementById('iaChatInput');
  const text  = (input.value||'').trim();
  if (!text) return;
  if (_iaChatHistory.length === 0) {
    alert('Clique em "Analisar Agora" primeiro para iniciar a análise.');
    return;
  }

  input.value = '';
  input.style.height = '44px';
  addChatMsg('user', text);
  _iaChatHistory.push({ role:'user', content: text });
  addThinking();

  const btn = document.getElementById('iaBtnEnviar');
  btn.disabled = true;

  try {
    const r = await callIaApi(_iaChatHistory);
    removeThinking();
    _iaChatHistory.push({ role:'assistant', content: r.text });
    addChatMsg('assistant', r.text, r.model);
  } catch(e) {
    removeThinking();
    addChatMsg('assistant', `❌ Erro: ${e.message}`);
  } finally {
    btn.disabled = false;
  }
}

function copyPrompt() {
  const prompt = buildAnalysisPrompt();
  navigator.clipboard.writeText(prompt).then(() => {
    const btn = event.target.closest('button');
    const orig = btn.innerHTML; btn.innerHTML = '✅ Copiado!';
    setTimeout(() => btn.innerHTML = orig, 2000);
  });
  const url = _iaProvider==='gemini'?'https://gemini.google.com/app':_iaProvider==='groq'?'https://chat.groq.com/':'https://chat.openai.com/';
  window.open(url,'_blank');
}
"""

html = html[:idx_start] + NEW_JS + html[idx_end:]

# ── Adicionar CSS da animação bounce no <style>
if '@keyframes bounce' not in html:
    html = html.replace('</style>', '''
@keyframes bounce { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-5px)} }
</style>''', 1)
    print("CSS bounce adicionado OK")

with open('dashboard_estoque.html','w',encoding='utf-8') as f:
    f.write(html)
print(f"Salvo OK — {len(html)//1024} KB")
print("JS substituido OK")
