#!/bin/bash

cat > "$HOME/Desktop/Renovar Andreani.command" << 'SCRIPT'
#!/bin/bash
cd ~/Downloads/andreani-link-v2

TOKEN_JSON=$(osascript -e '
tell application "Google Chrome"
  repeat with w in windows
    repeat with t in tabs of w
      if URL of t contains "pymes.andreani.com" then
        set r to execute t javascript "JSON.stringify(Object.entries(localStorage).filter(([k,v])=>v&&v.length>200&&(k.includes(\"msal\")||k.includes(\"token\")||k.includes(\"auth\")||v.startsWith(\"ey\"))).reduce((a,[k,v])=>({...a,[k]:v}),{}))"
        return r
      end if
    end repeat
  end repeat
  return "NO_TAB"
end tell')

if [ "$TOKEN_JSON" = "NO_TAB" ]; then
  open -a "Google Chrome" "https://pymes.andreani.com"
  sleep 6
fi

/usr/local/bin/node ~/Downloads/andreani-link-v2/setup.js

/usr/local/bin/node --input-type=module << 'JSEOF'
import { readFileSync } from 'fs';
const raw = JSON.parse(readFileSync(process.env.HOME + '/Downloads/andreani-link-v2/session/token_raw.json', 'utf8'));

// La clave correcta es partial:token (vence en 2031). pymes:token dura horas.
const token = raw['partial:token'];
if (!token) {
  console.error('No aparecio partial:token en el localStorage. Abortado para no pisar el token bueno.');
  process.exit(1);
}
const refreshToken = raw['refreshToken'] || '';
const r = await fetch('https://andreani-links.zohler.workers.dev/setup-tokens?secret=andreani2026', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({ token, refreshToken })
});
const d = await r.json();
if (!d.ok) { console.error('El Worker rechazo el token:', JSON.stringify(d)); process.exit(1); }
JSEOF

if [ $? -ne 0 ]; then
  osascript -e 'display dialog "No se pudo renovar. Revisar que la sesion de Andreani este abierta en Chrome." with title "Andreani" buttons {"OK"} default button "OK"'
  exit 1
fi

osascript -e 'tell application "Finder" to activate'
osascript -e 'display dialog "Tokens renovados exitosamente" with title "Andreani" buttons {"OK"} default button "OK"'
SCRIPT

chmod +x "$HOME/Desktop/Renovar Andreani.command"

osascript -e 'tell application "Finder" to activate'
osascript -e 'display dialog "Listo! Ya tenes Renovar Andreani en el Escritorio" with title "Instalacion completada" buttons {"OK"} default button "OK"'
