const HA_WS = process.env.HA_URL.replace('http://', 'ws://').replace('https://', 'wss://') + '/api/websocket';
const TOKEN = process.env.HA_TOKEN;
let msgId = 1;
const pending = {};
const ws = new WebSocket(HA_WS);

function send(msg) {
  return new Promise((resolve) => {
    const id = msgId++;
    msg.id = id;
    pending[id] = resolve;
    ws.send(JSON.stringify(msg));
  });
}

ws.addEventListener('message', ({ data }) => {
  const msg = JSON.parse(data);
  if (msg.type === 'auth_required') ws.send(JSON.stringify({ type: 'auth', access_token: TOKEN }));
  else if (msg.type === 'auth_ok') main().catch(e => { console.error(e); ws.close(); process.exit(1); });
  else if (msg.id && pending[msg.id]) { pending[msg.id](msg); delete pending[msg.id]; }
});

const newView = {
  title: "💡 Lumières",
  path: "gestion-lumieres",
  icon: "mdi:lightbulb-multiple",
  badges: [],
  cards: [
    // Carte résumé "tout contrôler"
    {
      type: "entities",
      title: "Toutes les lumières",
      show_header_toggle: true,
      entities: [
        { entity: "light.dimmer_2", name: "Entrée" },
        { entity: "light.bar", name: "Bar" },
        { entity: "light.bibliotheque", name: "Bibliothèque" },
        { entity: "light.dimmer_salon", name: "Salon" },
        { entity: "light.mezzanine", name: "Mezzanine" }
      ]
    },
    // Carte lumière individuelle avec curseur brightness
    {
      type: "light",
      entity: "light.dimmer_2",
      name: "Entrée"
    },
    {
      type: "light",
      entity: "light.bar",
      name: "Bar"
    },
    {
      type: "light",
      entity: "light.bibliotheque",
      name: "Bibliothèque"
    },
    {
      type: "light",
      entity: "light.dimmer_salon",
      name: "Salon"
    },
    {
      type: "light",
      entity: "light.mezzanine",
      name: "Mezzanine"
    },
    // Boutons rapides
    {
      type: "horizontal-stack",
      cards: [
        {
          type: "button",
          name: "Tout allumer",
          icon: "mdi:lightbulb-on",
          tap_action: {
            action: "call-service",
            service: "light.turn_on",
            target: {
              entity_id: [
                "light.dimmer_2",
                "light.bar",
                "light.bibliotheque",
                "light.dimmer_salon",
                "light.mezzanine"
              ]
            }
          }
        },
        {
          type: "button",
          name: "Tout éteindre",
          icon: "mdi:lightbulb-off",
          tap_action: {
            action: "call-service",
            service: "light.turn_off",
            target: {
              entity_id: [
                "light.dimmer_2",
                "light.bar",
                "light.bibliotheque",
                "light.dimmer_salon",
                "light.mezzanine"
              ]
            }
          }
        }
      ]
    }
  ]
};

async function main() {
  // 1. Lire la config actuelle
  const configResp = await send({ type: 'lovelace/config' });
  if (!configResp.result) throw new Error('Impossible de lire la config: ' + JSON.stringify(configResp.error));
  
  const config = configResp.result;
  console.log(`Config lue : ${config.views.length} vues`);
  
  // 2. Vérifier si "gestion-lumieres" existe déjà
  const exists = config.views.find(v => v.path === 'gestion-lumieres');
  if (exists) {
    console.log('Vue gestion-lumieres existe déjà — on va la remplacer');
    const idx = config.views.indexOf(exists);
    config.views[idx] = newView;
  } else {
    config.views.push(newView);
    console.log(`Nouvelle vue ajoutée → total: ${config.views.length} vues`);
  }
  
  // 3. Sauvegarder
  const saveResp = await send({
    type: 'lovelace/config/save',
    config: config
  });
  
  if (saveResp.type === 'result' && saveResp.success) {
    console.log('✅ Config sauvegardée avec succès !');
    console.log('URL: ' + process.env.HA_URL + '/lovelace/gestion-lumieres');
  } else {
    console.log('❌ Erreur:', JSON.stringify(saveResp, null, 2));
  }
  
  ws.close();
}

ws.addEventListener('error', e => { console.error('WS Error:', e.message); process.exit(1); });
setTimeout(() => { console.error('Timeout'); process.exit(1); }, 15000);
