import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const TAURI_CONF = path.resolve(__dirname, '../src-tauri/tauri.conf.json')
const OUTPUT = path.resolve(__dirname, '../updater.json')

const PLATFORM = 'windows-x86_64'
const BASE_URL = 'https://git.koptilnya.xyz/opti1337/chad/releases/download/latest'

const tauriConfRaw = fs.readFileSync(TAURI_CONF, 'utf8')
const tauriConf = JSON.parse(tauriConfRaw)
const version = tauriConf.version

const SIG_FILE = path.resolve(
  __dirname,
  `../src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/chad_${version}_x64-setup.exe.sig`,
)

const signature = fs.readFileSync(SIG_FILE, 'utf8').trim()

const installerName = `chad_${version}_x64-setup.exe`

const updater = {
  pub_date: new Date().toISOString(),
  version,
  platforms: {
    [PLATFORM]: {
      url: `${BASE_URL}/${installerName}`,
      signature,
    },
  },
  notes: '',
}

fs.writeFileSync(OUTPUT, JSON.stringify(updater, null, 2), 'utf8')

console.log('updater.json generated')
