import Database from "better-sqlite3";
import { XMLParser } from "fast-xml-parser";

const DB_PATH = process.env.FUZ_DB_PATH || "./src/data/ServicesRange.db";

const SOURCES = [
  {
    kind: "premium",
    url: "https://www.jambox.pl/xml/slownik-pakietypremium.xml",
  },
  {
    kind: "tematyczne_plus",
    url: "https://www.jambox.pl/xml/slownik-pakietytematyczneplus.xml",
  },
];

async function fetchXml(url) {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(
      `Błąd pobierania XML z ${url}: ${res.status} ${res.statusText}`
    );
  }
  return await res.text();
}

function parseNodesFromXml(xmlText) {
  const parser = new XMLParser({
    ignoreAttributes: false,
    attributeNamePrefix: "@_",
  });

  const json = parser.parse(xmlText);
  let nodes = json.xml?.node ?? json.node ?? [];

  if (!nodes) return [];
  if (!Array.isArray(nodes)) nodes = [nodes];
  return nodes;
}

function ensureSchema(db) {
  db.exec(`
    CREATE TABLE IF NOT EXISTS jambox_tv_addons (
      tid         INTEGER PRIMARY KEY,
      name        TEXT    NOT NULL,
      kind        TEXT    NOT NULL,
      is_active   INTEGER NOT NULL DEFAULT 1,
      updated_at  TEXT    NOT NULL
    );
  `);
}

function upsertTvAddons(db, kind, nodes) {
  const now = new Date().toISOString();

  const upsert = db.prepare(`
    INSERT INTO jambox_tv_addons (tid, name, kind, is_active, updated_at)
    VALUES (@tid, @name, @kind, 1, @updated_at)
    ON CONFLICT(tid) DO UPDATE SET
      name       = excluded.name,
      kind       = excluded.kind,
      is_active  = excluded.is_active,
      updated_at = excluded.updated_at;
  `);

  const tx = db.transaction((rows) => {
    let ok = 0;

    for (const node of rows) {
      const name = node.name ?? node.nazwa ?? node["#text"] ?? "";
      const tidRaw = node.tid ?? node.id ?? null;

      if (!tidRaw || !name) {
        console.warn(`⚠ Pomijam node bez tid/name (kind=${kind}):`, node);
        continue;
      }

      const tid = Number(tidRaw);
      if (!Number.isFinite(tid) || tid <= 0) {
        console.warn(`⚠ Pomijam node z niepoprawnym tid (kind=${kind}):`, node);
        continue;
      }

      upsert.run({
        tid,
        name: String(name).trim(),
        kind,
        updated_at: now,
      });

      ok++;
    }

    console.log(`✅ ${kind}: zapisano/zmieniono ${ok} rekordów.`);
  });

  tx(nodes);
}

async function main() {
  console.log(`Używam bazy: ${DB_PATH}`);
  const db = new Database(DB_PATH);

  ensureSchema(db);

  for (const { kind, url } of SOURCES) {
    console.log(`\n=== Przetwarzam ${kind} (${url}) ===`);

    try {
      const xml = await fetchXml(url);
      const nodes = parseNodesFromXml(xml);

      console.log(`📦 Znaleziono ${nodes.length} node'ów (kind=${kind})`);
      upsertTvAddons(db, kind, nodes);
    } catch (err) {
      console.error(`❌ Błąd przy imporcie ${kind}:`, err);
    }
  }

  db.close();
  console.log("\n🎉 Import słowników pakietów dodatkowych zakończony.");
}

main().catch((err) => {
  console.error("❌ Krytyczny błąd:", err);
  process.exit(1);
});
