import { JSDOM } from "jsdom";
import fs from "node:fs";


if (process.argv.length !== 4) {
  console.log("USAGE: node fix-weblate-format.js <file> <lang>")
  console.log("")
  console.log("file: location of the XLIFF file exported by weblate")
  console.log("lang: 2 char lang code like 'es' 'en' 'fr' of the XLIFF file")
  process.exit(1)
}

const FILE_NAME = process.argv[2]
const LANG_CODE = process.argv[3]

// read the file like 'gnu-taler-taler-wallet-ios-fr.xlf'
const data = fs.readFileSync(FILE_NAME, 'utf8');

const dom = new JSDOM(data, {
  contentType: "text/xml",
});

// gather all the translations
const units = Array.from(dom.window.document.getElementsByTagName("trans-unit"))
const files = {} //Record<string, Element[]>

// create a mapping fileName => translations element
units.forEach(element => {
  const [fileName, idName] = element.getAttribute("id").split("///")
  if (!fileName.startsWith("TalerWallet1/")) {
    // skip non talerwallet keys
    return;
  }

  // initialize result set for this file if there is not one yet
  if (!files[fileName]) {
    files[fileName] = []
  }

  // get elementByTagName returns a collection but we expect
  // to have no more than one target element
  if (element.getElementsByTagName("target").length === 0 || !element.getElementsByTagName("target")[0]) {
    // skip element without target element: without transaltion
    return;
  }
  const targetChild = element.getElementsByTagName("target")[0];
  if (!targetChild.hasChildNodes()) {
    // skip element with empty translation
    return;
  }

  // cleanup the id attr
  element.removeAttribute("id")
  if (idName) {
    element.setAttribute("id", idName)
  }
  const str = element.outerHTML
  // cleanup xmlns
  const clean = str.replace(` xmlns="urn:oasis:names:tc:xliff:document:1.1"`, "")

  files[fileName].push(clean)
});

// fixed header and footer
const XLF_HEADER = `<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 http://docs.oasis-open.org/xliff/v1.2/os/xliff-core-1.2-strict.xsd">`
const XLF_FOOTER = `</xliff>`

// header and footer by file translated
const FILE_HEADER = (fileName) => `  <file original="${fileName}" source-language="en" target-language="${LANG_CODE}" datatype="plaintext">
    <header>
      <tool tool-id="com.apple.dt.xcode" tool-name="Xcode" tool-version="15.4" build-num="15F31c"/>
    </header>
    <body>`
const FILE_FOOTER = `    </body>
  </file>`

// render the content to the standard output
console.log(XLF_HEADER)
Object.keys(files).forEach(fileName => {
  console.log(FILE_HEADER(fileName))
  const elements = files[fileName];
  elements.forEach(element => {
    console.log("      " + element)
  })
  console.log(FILE_FOOTER)
})
console.log(XLF_FOOTER)

