// Assicurati di avere "type": "module" nel package.json
// oppure salva il file come .mjs

import fs from "fs";
import path from "path";


const root = "./home/sites";                  // cartella principale
const outputFile = "./home/sites.json";  // file di output
const iconsDir = "./home/icons";         // cartella dove salvare le icone
const baseDir = "./home";



/**
 * Cancella un'icona dato il path relativo (es. "icons/composerize.ico")
 * @param {string} iconPath - Percorso relativo dell'icona rispetto a baseDir
 */
function deleteIconSync(iconPath) {
  try {
    const fullPath = path.join(baseDir, iconPath);
    fs.unlinkSync(fullPath);
    console.log(`Cancellato: ${fullPath}`);
  } catch (err) {
    if (err.code === "ENOENT") {
      console.error("File non trovato:", iconPath);
    } else {
      console.error("Errore durante la cancellazione:", err);
    }
  }
}








function parseSite(folder) {
  const sitePath = path.join(root, folder);
  let shortName = folder; // fallback
  let iconPath = null;

  // 1. Cerca manifest.json
  const manifestPath = path.join(sitePath, "manifest.json");
  if (fs.existsSync(manifestPath)) {
    try {
      const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
      if (manifest.short_name) shortName = manifest.short_name;
      if (manifest.icons && manifest.icons.length > 0) {
        iconPath = path.join(sitePath, manifest.icons[0].src);
      }
    } catch (e) {}
  }

  // 2. Se non c’è manifest, prova index.html
  const indexPath = path.join(sitePath, "index.html");
  if (!iconPath && fs.existsSync(indexPath)) {
    const html = fs.readFileSync(indexPath, "utf8");
    const titleMatch = html.match(/<title>(.*?)<\/title>/i);
    if (titleMatch) shortName = titleMatch[1];

    const iconMatch = html.match(/<link[^>]+rel=["']icon["'][^>]+href=["']([^"']+)["']/i);
    if (iconMatch) {
      iconPath = path.join(sitePath, iconMatch[1]);
    }
  }

  // 3. Fallback su favicon.ico
  const faviconPath = path.join(sitePath, "favicon.ico");
  if (!iconPath && fs.existsSync(faviconPath)) {
    iconPath = faviconPath;
  }

  // 4. Copia l’icona nella cartella comune
  let finalIcon = "icons/default.png"; // path pulito
  if (iconPath && fs.existsSync(iconPath)) {
    const ext = path.extname(iconPath) || ".png";
    const dest = path.join(iconsDir, `${folder}${ext}`);
    try {
      fs.copyFileSync(iconPath, dest);
      finalIcon = `icons/${folder}${ext}`; // solo riferimento relativo
    } catch (e) {
      console.error(`Errore copia icona per ${folder}:`, e);
    }
  }

  return { dir: folder, name: shortName, icon: finalIcon };
}

export function generateSitesJson() {
  // crea la cartella icons se non esiste
  if (!fs.existsSync(iconsDir)) {
    fs.mkdirSync(iconsDir, { recursive: true });
  }

  // Scansiona tutte le sottocartelle (escludendo home e icons)
  const sites = fs.readdirSync(root).filter(f =>
    fs.statSync(path.join(root, f)).isDirectory() && f !== "home" && f !== "icons"
  );
  console.log("leggo i siti:", sites);
  //console.log("primo sito", parseSite(sites[0]));
  // Estrarre info
  const results = sites.map(parseSite);

  // Salva in JSON
  fs.writeFileSync(outputFile, JSON.stringify(results, null, 2), "utf8");
  results.unshift({ dir: 'home', name: 'Home', icon: 'home.ico' });
  console.log(`✅ File JSON salvato in ${outputFile}`);
  return results;
}

// elimina dal file sites.json gli oggetti con dir = "a"
export function delFieldDir(dir) {
  if (!fs.existsSync(outputFile)) {
    console.error("❌ File non trovato:", outputFile);
    return;
  }

  try {
    const data = fs.readFileSync(outputFile, "utf8");
    const results = JSON.parse(data);

    const filt = results.filter(item => item.dir == dir);
    //console.log("icona da canc: ",filt);
    console.log("icona da canc: ",filt[0].icon);
    deleteIconSync(filt[0].icon);
    // filtra via gli elementi con directory = dir
    const filtered = results.filter(item => item.dir !== dir);
    //console.log("nuovo sites.json", filtered);
    fs.writeFileSync(outputFile, JSON.stringify(filtered, null, 2), "utf8");
    console.log(`✅ File aggiornato: rimossi i campi con dir = ${dir}`);
    filtered.unshift({ dir: 'home', name: 'Home', icon: 'home.ico' });
    return filtered;
  } catch (e) {
    console.error("Errore durante la modifica del file:", e);
  }
}

export function addFieldDir(dir) {
  if (!fs.existsSync(outputFile)) {
    console.error("❌ File non trovato:", outputFile);
    return;
  }

  try {
    const data = fs.readFileSync(outputFile, "utf8");
    const results = JSON.parse(data);
    //console.log("sito agg",parseSite(dir));
    // aggiungi elemonto elementi con directory = dir
    results.push(parseSite(dir));
    //console.log("add site nuovo sites.json", results);
    //const filtered = results.filter(item => item.dir !== dir);
    //console.log("nuovo sites.json", filtered);
    fs.writeFileSync(outputFile, JSON.stringify(results, null, 2), "utf8");
    results.unshift({ dir: 'home', name: 'Home', icon: 'home.ico' });
    console.log(`✅ File aggiornato: rimossi i campi con dir = ${dir}`);
    return results;
  } catch (e) {
    console.error("Errore durante la modifica del file:", e);
  }
}
